How do I remove multiple elements from an array by index?

Viewed 12052

Using a Array.splice is fine as long as it's a single value. Suppose I have an array with 10 elements and I want to remove element 2,4 and 8, using Array.splice(index,1) in a for loop is a bad idea because the index of each element changes after each splice operation.

How can I remove specific array items and then re-arrange the array accordingly

var array = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];

remove(array, 4,5); //Is there a lodash function for this?

//desired result --> ["Apple", "Banana", "Peach", "Guava"]
3 Answers

The approach you need to take is, removing the elements in a backward manner (not reversing the array, as that has the same underlying problem of decrementing the indices of 'not yet checked' elements upon removal.

You can use the reduceRight method, which acts very much like Reduce, but instead, it iterates an array from (right to left).

Here is an example of how this could be done:

var array = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];

let indexToRemove = [4, 5]; //We're looking to remove "Tomato" & "Mango"

array.reduceRight((_, elem, index) => {
    if (indexToRemove.includes(index)) { //Our condition(s)
        array.splice(index, 1);
    }
});

console.log(array); //Result: [ 'Apple', 'Banana', 'Peach', 'Pumpkin', 'Guava' ]
Related