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;
}
That's because
0
is a falsy value in JavaScript.this[i]
will be falsy if the value of the array is 0 or any other falsy value.This will work.
I have since found a nice method that uses jQuery
Note: This code was pulled from Paul Irish's duck punching post - I forgot to give credit :P
We can do this using ES6 sets:
//The output will be
You can also use jQuery
Originally answered at: jQuery function to get all unique elements from an array?
Building on other answers, here's another variant that takes an optional flag to choose a strategy (keep first occurrence or keep last):
Without extending
Array.prototype
Extending
Array.prototype