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?