One way to remove multiple elements from a JavaScript array is to use a for -of loop.
For instance, we can write:
const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
removeValFromIndex = [0, 2, 4];
for (const i of removeValFromIndex.reverse()) {
valuesArr.splice(i, 1);
}
console.log(valuesArr)
We have the valuesArr
with the items we want to remove.
removeValFromIndex
has the indexes with the indexes of valuesArr
that we want to remove.
Then we loop through the removeValFromIndex
backwards with reverse
and the for-of loop and remove each item with splice
.
We’ve to loop backwards so that we won’t mess up the indexes for items that are yet to be removed.
Therefore, valuesArr
is [“v2”, “v4”]
.
Use Array.prototype.filter
Also, we can use the JavaScript array filter
method to remove items from the array given the indexes of the items we want to remove.
For instance, we can write:
const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
removeValFromIndex = [0, 2, 4];
const filtered = valuesArr.filter((value, index) => {
return !removeValFromIndex.includes(index);
})
console.log(filtered)
We call filter
with a callback that has the index
parameter as the 2nd parameter.
Then we call includes
with index
to see if the index
isn’t in removeValFromIndex
.
If it’s not, then we keep the item with the given index in the returned array.
Therefore, filtered
is [“v2”, “v4”]
.