views:

222

answers:

4

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;
}

Edit: Opps, I accidentally removed the a in return a

A: 

Don't quote me on this but I think that you need to use a string for your property name, like o[e.toString()], and then convert it back when you push it.

Edit: removed dumb mistake.

danben
+3  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.

Luca Matteis
Right, and that would be why. +1
danben
Ahhhh, ok I see now... but would there be an easy fix to make it work?
fudgey
A: 
Array.prototype.getUnique = function() {
    var o = {}, a = []
    for (var i = 0; i < this.length; i++) o[this[i]] = 1
    for (var e in o) a.push(e)
    return a
}
ephemient
+2  A: 

There is no need to use 2 for loops, just put one small if statement inside loop

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(this[i] in u)
         continue;
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}
Rafael
Thank you and Merry Christmas!
fudgey