Sometimes, we want to remove element from array in forEach loop with JavaScript.
In this article, we’ll look at how to remove element from array in forEach loop with JavaScript.
How to remove element from array in forEach loop with JavaScript?
To remove element from array in forEach loop with JavaScript, we can use the array splice
method.
For instance, we write
const review = ["a", "b", "c", "b", "a"];
review.forEach((item, index, arr) => {
if (item === "a") {
arr.splice(index, 1);
}
});
to call review.forEach
with a callback that checks if the item
we’re iterating through is 'a'
.
If it is, then we call arr.splice
with index
and 1 to remove the review
entry at index
.
Conclusion
To remove element from array in forEach loop with JavaScript, we can use the array splice
method.
One reply on “How to remove element from array in forEach loop with JavaScript?”
Wrong, try:
const review = [“a”, “a”, “b”, “c”, “b”, “a”];