Javascript remove all occurrence of duplicate element, leaving the only one that is unique

This should do the trick:

Array.prototype.getUnique = function(){
    var uniques = [];
    for(var i = 0, l = this.length; i < l; ++i){
        if(this.lastIndexOf(this[i]) == this.indexOf(this[i])) {
            uniques.push(this[i]);
        }
    }
    return uniques;
}

// Usage:

var a = [2, 6, 7856, 24, 6, 24];
alert(JSON.stringify(a.getUnique()));

console.log(a.getUnique()); // [2, 7856]

To check if a specific item is unique in the array, it just checks if the first index it’s found at, matches the last index it’s found at.

Leave a Comment