Here are 4 variants:
const array = ['a', 'b', 'b', 'c', 'c'];
using JavaScript of the future
const unique = [...new Set(array)];
As @stderr you mentioned in his answer are already planned (not yet officially released) two concepts that can be used to the end of the question. One is the Set , which is a new way to organize iterables. The other is the spread syntax that allows you to render / convert iterable, more or less as an indication to write the object "in extenso". In this case combining the two, gives what is asked in the question.
This solution still solves the problem that Gabriel mentioned and that exists in the solution with .filter()
. (example: link )
Using .filter
:
const unique = array.filter((el, i, arr) => arr.indexOf(el) == i);
console.log(unique); // ["a", "b", "c"]
The .filter
method is natively available to arrays and accepts a function (callback). This function receives 3 arguments: the element to be iterated, the index (position) that is being iterated, and the original array. Using arr.indexOf(el) == i
we ensure that only the first time each duplicate appears resolves to true
, thus clearing the other elements.
Using .reduce
and a ternary checker.
const unique = array.reduce(
(arr, el) => arr.concat(arr.includes(el) ? [] : [el]), []
);
console.log(unique); // ["a", "b", "c"]
In this case with .reduce
we can join elements to an array initialized in the second argument of the reduce
method. It iterates all the positions of the array and with the ternary we check if the element already exists in the new array that is being created within the array.
Using an object to avoid duplicating keys
(only useful when we use Primitives )
const unique = ((obj, arr) => {
arr.forEach(el => obj[el] = true);
return Object.keys(obj);
})({}, array);
console.log(unique); // ["a", "b", "c"]
In this case we populate an object with keys formed by the elements of the initial array. Since objects only allow unique keys, when the iteration is complete we can return Object.keys(obj)
which gives a new array with these unique keys.