Reputation: 2107
I am trying to write the logic to delete element by passing indexArr(that contains indexes to delete) to a method:
var a = [0,1,2,3,4,5];
Array.prototype.removeElem = function(indexArr){
this.filter(function(value,index,arr){
return indexArr.indexOf(index)>-1 ? arr[index] = undefined:false
}
});
}
a.removeElem([2,3]); //passing indexes in form of array
console.log(a.join('').split('')); //removing undefined values
As you can see, I am removing undefined
values after the execution of removeElem()
method, but I want to do that in the method itself.
Upvotes: 0
Views: 78
Reputation: 648
EDIT:
var a = [0,1,2,3,4,5];
Array.prototype.removeElem = function(indexArr){
indexArr.sort();
i=indexArr.length;
while(i--)
{
a.splice(indexArr[i],1);
}
}
a.removeElem([2,3]); //passing indexes in form of array
console.log(a);
Upvotes: 1
Reputation: 4523
No need to use Array.filter()
. Try something like this :
let a = [0, 1, 2, 3, 4, 5];
Array.prototype.removeElem = function(indexArr) {
let removedElem = 0;
for (let i = 0; i < indexArr.length; i++) {
this.splice(indexArr[i] - removedElem, 1)
removedElem += 1;
};
return this;
}
console.log(a.removeElem([2, 3]));
simple :)
Upvotes: 1
Reputation: 11291
To modify an original array, you can use while()
loop from last to first index combined with splice()
method:
var a = [0,1,2,3,4,5];
Array.prototype.removeElem = function(indexArr){
var length = this.length;
while(length--) {
if(indexArr.indexOf(length) > -1) {
this.splice(length, 1);
}
}
}
console.log(a.removeElem([0,1]));
console.log(a);
Upvotes: 2
Reputation: 7498
you can make use of reduce for this.
check the following code snippet
var a = [0, 1, 2, 3, 4, 5];
Array.prototype.removeElem = function(indexArr) {
return this.reduce((result, key, index) => {
if (indexArr.indexOf(index) === -1) {
result.push(key)
}
return result
}, [])
}
var result = a.removeElem([2, 3]); //passing indexes in form of array
console.log(result.join('').split(''));
Hope it helps
Upvotes: 0