0

I want to attach a new method to the Array.prototype:

Array.prototype.uniq = function(){
  return this.filter((val, index) => {
    return this.indexOf(val) === index;
  });
};

var a = [1, 1, 2, 3];
console.log(a.uniq()); // output: [1,2,3]
console.log(a); // output: [1,1,2,3]

The method removes duplicates from an array. The problem I have is that whenever uniq is called, a new array is returned. I want to do something like this:

Array.prototype.uniq = function(){
  this = this.filter((val, index) => {  // "ReferenceError: Invalid left-hand side in assignment
    return this.indexOf(val) === index;
  });
};

so that:

var a = [1, 1, 2, 3];
a.uniq();
console.log(a); // output: [1,2,3]

What should I do?

Cheng
  • 16,824
  • 23
  • 74
  • 104

1 Answers1

4

You can iterate over the array using for loop and use splice if the index are not same.

Array.prototype.uniq = function () {
    // Reverse iterate
    for (var i = this.length - 1; i >= 0; i--) {

        // If duplicate
        if (this.indexOf(this[i]) !== i) {
            // Remove from array
            this.splice(i, 1);
        }
    }

    // Return updated array
    return this;
};

var a = [1, 1, 2, 3];
a.uniq();
console.log(a); // output: [1,2,3]
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    Thx! I thought about splice but the index changes as I remove elements from the array. Reverse iterate is very smart :) The `return this` line is not needed right? – Cheng May 19 '16 at 15:51
  • Tushar, shouldn't the indexes inside the for loop be `i-1` because `i = this.length` makes `this[i]` out of the loop. – Cheng May 21 '16 at 12:08