Categories
JavaScript Answers

How to Remove Objects from a JavaScript Array by Object Property?

Spread the love

Sometimes, we want to remove an object from a JavaScript array that has the given property value.

In this article, we’ll look at how to remove objects from a JavaScript array given a property value.

Using the Array.prototype.splice and Array.prototype.findIndex Methods

We can use the JavaScript array findIndex method to find the index of the object in an array with the given property value.

Then we can use the JavaScript array splice method to remove the item with the index returned by findIndex .

For instance, we can write:

const items = [{
    id: 'abc',
    name: 'oh'
  },
  {
    id: 'efg',
    name: 'em'
  },
  {
    id: 'hij',
    name: 'ge'
  }
];
const index = items.findIndex((i) => {
  return i.id === "abc";
})
items.splice(index, 1);
console.log(items)

We have the items array with a bunch of objects.

And we want to remove the one with id set to 'abc' .

To do that, we call items.findIndex with a callback that returns id.id === 'abc' so we can get the index of the object with the id set to 'abc' .

Then we can call items.splice with the index and 1 to remove the item at the given index from items .

Therefore, items is now:

[
  {
    "id": "efg",
    "name": "em"
  },
  {
    "id": "hij",
    "name": "ge"
  }
]

Conclusion

We can use the findIndex method to find the index of an object in an array that meets the given condition.

Then we can use the splice method to remove the item at the index returned by findIndex to remove the item from the array.

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 *