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?

3

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Tushar, shouldn't the indexes inside the for loop be i-1 because i = this.length makes this[i] out of the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.