Last Updated: February 25, 2016
·
2.597K
· iam4x

Unique values in JavaScript Arrays

A snippet I use frequently to remove the duplicates entry in my arrays, it's an extension of the array class.

Array.prototype.unique = function () {
    var r = [];
    o:for(var i = 0, n = this.length; i < n; i++)
    {
        for(var x = 0, y = r.length; x < y; x++)
      {
        if(r[x]===this[i])
        {
          continue o;
        }
      }
      r[r.length] = this[i];
    }
    return r;
};

Use it this way : [1, 2, 3, 4, 1].unique()

It will return : [1, 2, 3, 4]

Happy coding!

5 Responses
Add your response

I think you should use strict comparison here

if(r[x]===this[i])
over 1 year ago ·

Or you can try something like this

[1, 2, 3, 4, 1].filter(function(item, index, all){
    return all.lastIndexOf(item) === index;
});
over 1 year ago ·

@dpashkevich Yep, you're right. Thanks.

over 1 year ago ·

@avenger7x Good solution, but slow one. I'm doing JavaScript on iOS devices and that sucks... I did a JSPerf to compare : http://jsperf.com/uniquearraycoderwall

over 1 year ago ·

@iam4x yep, it's slower than your solution, but when you haven't time to implement some new stuff like this you can just filter array :)

over 1 year ago ·