I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on SO that looks almost exactly like it, but it doesn't fail.
So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
Simplest solution:
Or:
To address the problem the other way around, it may be useful to have no duplicate while you load your array, the way Set object would do it but it's not available in all browsers yet. It saves memory and is more efficient if you need to look at its content many times.
Sample:
Gives you
set = [1,3,4,2]
This prototype
getUnique
is not totally correct, because if i have a Array like:["1",1,2,3,4,1,"foo"]
it will return["1","2","3","4"]
and"1"
is string and1
is a integer; they are different.Here is a correct solution:
using:
The above will produce
["1",2,3,4,1,"foo"]
.Without extending Array.prototype (it is said to be a bad practice) or using jquery/underscore, you can simply
filter
the array.By keeping last occurrence:
or first occurrence:
Well, it's only javascript ECMAScript 5+, which means only IE9+, but it's nice for a development in native HTML/JS (Windows Store App, Firefox OS, Sencha, Phonegap, Titanium, ...).
Using object keys to make unique array, I have tried following
Which returns
["1", 1, 2, 3, 4, "foo", false, null]
You can also use underscore.js.
which will return: