How to get an array of unique values from an array containing duplicates in JavaScript?

NaveenDAlmeida picture NaveenDAlmeida · Nov 21, 2012 · Viewed 157.1k times · Source

Given a ['0','1','1','2','3','3','3'] array, the result should be ['0','1','2','3'].

Answer

Pedro L. picture Pedro L. · Jul 28, 2013

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;
    }, []);
};