Misha Moroshko
Misha Moroshko

Reputation: 171321

Javascript "unique()" function

I added unique() function to Javascript Array:

Array.prototype.unique = function(){
  return this.filter(function(item, ind, arr){
    return ind == arr.lastIndexOf(item);
  });
};

but when I iterate like this:

for (i in arr) { ... }

i becomes unique as well:

var arr = [1, 2, 1];
for (i in arr) {
    console.log(i + " ===> " + arr[i]);
}

// 0 ===> 1
// 1 ===> 2
// 2 ===> 1
// unique ===> function () { return this.filter(function (item, ind, arr) {return ind == arr.lastIndexOf(item);}); }

I know that I can iterate like this:

for (i = 0; i < arr.length; i++) { ... }

However, I still wonder if it's possible to add functions to Array and iterate like this:

for (i in arr) { ... }

?

Upvotes: 2

Views: 2037

Answers (1)

taskinoor
taskinoor

Reputation: 46027

You can make the unique property non-enumerable.

Object.defineProperty(Array.prototype, "unique", { enumerable : false,
                                                  configurable : true});

Upvotes: 5

Related Questions