Here are 4 variants:
const array = ['a', 'b', 'b', 'c', 'c'];
using Javascript from the future
const unique = [...new Set(array)];
Like the @stderr referred in his answer are already planned (not yet officially launched) two concepts that can be used for the purpose of the question. One of them the Set, which is a new way of organizing eternal. The other is the spread syntax which allows to represent/convert eternal, more or less as an indication to write the object "in full". In this case combining the two, gives what is asked in the question.
This solution also resolves the problem that Gabriel mentioned and which exists in the solution with .filter()
. (example: http://www.es6fiddle.net/iskjh2q8/)
Using .filter
:
const unique = array.filter((el, i, arr) => arr.indexOf(el) == i);
console.log(unique); // ["a", "b", "c"]
The method .filter
is natively available for arrays and accepts a function (callback). This function takes 3 arguments: the element to be iterated, the index (position) being iterated, and the original array. Using arr.indexOf(el) == i
we guarantee that only the first time that each duplicate appears solves how true
, thus cleaning the other elements.
Using .reduce
and a ternary verifier.
const unique = array.reduce(
(arr, el) => arr.concat(arr.includes(el) ? [] : [el]), []
);
console.log(unique); // ["a", "b", "c"]
In this case with the .reduce
we can join elements to an initialized array in the second argument of the method reduce
. It iterates all array positions and with ternary we check whether the element already exists in the new array being created within reduce.
Using an object to avoid duplicating keys
(only useful when we use Primitive)
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.
More answers in this duplicate.
– Luiz Felipe