Categories
JavaScript Answers

How to filter and delete filtered elements in an array with JavaScript?

Spread the love

To filter and delete filtered elements in an array with JavaScript, we use the splice and findIndex methods.

For instance, we write

const a = [{ name: "tc_001" }, { name: "tc_002" }, { name: "tc_003" }];
a.splice(
  a.findIndex((e) => e.name === "tc_001"),
  1
);

to call a.findIndex with a callback that checks if name is 'tc_001' in the object being looped through to get the index with name property equal to ‘tc_001’ina`.

Then we call splice with the index and 1 to remove the item in a with such condition.

By John Au-Yeung

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

Leave a Reply

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