Get all unique values in a JavaScript array

  1. Use Object {} to prevent dulicates
  2. Use helper array []
  3. Use filter + indexOf
  4. Use ES6 […new Set()]

Use Object {} to prevent dulicates

1
2
3
4
5
6
7
function uniqueArray1(arr) {
const obj = {};
arr.forEach((element) => {
obj[typeof element + element] = element;
});
return Object.keys(obj).map((item) => obj[item]);
}

Use helper array []

1
2
3
4
5
6
7
8
9
10
function uniqueArray2(arr) {
var result = [];
for (var i = 0, len = arr.length; i < len; i++) {
var element = arr[i];
if (result.indexOf(element) === -1) {
result.push(element);
}
}
return result;
}

Use filter + indexOf

1
2
3
4
5
function uniqueArray3(arr) {
return arr.filter(function (value, index, array) {
return array.indexOf(value) === index;
});
}

Use ES6 […new Set()]

1
2
3
function uniqueArray4(arr) {
return [...new Set(arr)];
}