Ayush Sharma
Ayush Sharma

Reputation: 2107

How to delete elements from an array from different indexes by single method?

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

Answers (5)

Dilip Belgumpi
Dilip Belgumpi

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

m87
m87

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

wscourge
wscourge

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

Geeky
Geeky

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

Vikram Singh
Vikram Singh

Reputation: 972

use splice method to add and remove element from array

Upvotes: -2

Related Questions