How to get an array of unique values from an array containing duplicates in JavaScript? [duplicate]
Edited
ES6 solution:
[...new Set(a)];
Alternative:
Array.from(new Set(a));
Old response. O(n^2) (do not use it with large arrays!)
var arrayUnique = function(a) {
return a.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
};
If you want to maintain order:
arr = arr.reverse().filter(function (e, i, arr) {
return arr.indexOf(e, i+1) === -1;
}).reverse();
Since there's no built-in reverse indexof, I reverse the array, filter out duplicates, then re-reverse it.
The filter function looks for any occurence of the element after the current index (before in the original array). If one is found, it throws out this element.
Edit:
Alternatively, you could use lastindexOf (if you don't care about order):
arr = arr.filter(function (e, i, arr) {
return arr.lastIndexOf(e) === i;
});
This will keep unique elements, but only the last occurrence. This means that ['0', '1', '0'] becomes ['1', '0'], not ['0', '1'].
Here is an Array Prototype function:
Array.prototype.unique = function() {
var unique = [];
for (var i = 0; i < this.length; i++) {
if (unique.indexOf(this[i]) == -1) {
unique.push(this[i]);
}
}
return unique;
};
With underscorejs
_.uniq([1, 2, 1, 3, 1, 4]); //=> [1, 2, 3, 4]