mll1kw
Last Updated: February 25, 2016
·
1.896K
· 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!

Say Thanks
Respond

5 Responses
Add your response

4571
D42a7264714dee5006b9c99d2567a320

I think you should use strict comparison here

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

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 ·
4573

@dpashkevich Yep, you're right. Thanks.

over 1 year ago ·
4574

@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 ·
4578

@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 ·
Awesome Job

B6c77ad0 c95b 11e7 8263 8f89080b8db6
Ruby Developer Backend
·
Austria (Vienna or Linz)
·
Full Time