Sometimes, we want to remove multiple elements from array in JavaScript.
In this article, we’ll look at how to remove multiple elements from array in JavaScript.
How to remove multiple elements from array in JavaScript?
To remove multiple elements from array in JavaScript, we can use the array filter
method.
For instance, we write
let valuesArr = ["v1", "v2", "v3", "v4", "v5"];
const removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter((value, index) => {
return removeValFrom.indexOf(index) === -1;
});
to call valueArr.filter
with a callback that checks if the index
of the element in valuesArr
is in the removeValFrom
array which has the indexes of the items in valuesArr
that we want to remove.
A new array with the items that we want to keep are included, so we assign the array back to valuesArr
.
Conclusion
To remove multiple elements from array in JavaScript, we can use the array filter
method.