Categories
JavaScript Answers

How to remove element from array in forEach loop with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to remove element from array in forEach loop with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *