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!
Written by iam4x
Related protips
5 Responses
I think you should use strict comparison here
if(r[x]===this[i])Or you can try something like this
[1, 2, 3, 4, 1].filter(function(item, index, all){
return all.lastIndexOf(item) === index;
});@dpashkevich Yep, you're right. Thanks.
@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
@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 :)
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside