.splice() array with array of non-sequential indexes - javascript

1.6k views Asked by At

I have an array like this

Array['one','two','three','four','five']

and I have an array like this

Array['2','4','0']

indicating the indexes of the elements in the first array I wish to remove or .splice() so the resulting array would look like this

Array['two','four']  // <--- note no undefined positions

If you try and loop through the indexes and just do a splice for each one, after the first splice your indexes change according to the element that was removed.

How can I accomplish this?

1

There are 1 answers

2
Sachin Shanbhag On BEST ANSWER

You can start splicing the indexes from the array in reverse order. i.e. Loop from the length of array to 0.

First splice index 4 and then index 2.

EDIT: As you mentioned the indexes array need not be in same order, you can sort the indexes array in ascending order and then implement the above logic.