Reputation: 17894
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?
Upvotes: 0
Views: 139
Reputation: 87203
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]
Upvotes: 4