Remove item from an array of objects by object property in JavaScript

in Code Write a comment

Learn the easy way to remove an element from an array of objects by object property in JavaScript/Vue.js/ES6.

Suppose you have an array of objects, like the one below:

items: [
  { id: 1, text: "Item 1" },
  { id: 2, text: "Item 2" },
  { id: 3, text: "Item 3" }
]

Your goal is to remove an object from this array that has an id 2. You can do that by using the JavaScript filter() method.

this.items = this.items.filter((obj) => {
  return obj.id !== 2;
})

JavaScript filter() method

JavaScript filter() method creates a new array with the items that pass the condition by the provided function.


Hi, I'm Renat 👋

âžœ  


In the example above we filter out all the objects that have an ID other than 2.

return obj.id !== 2;

Since the filter() method creates a new array, we can replace our existing array with the new one in a single command.

this.items = this.items.filter((obj) => {
  return obj.id !== 2;
})

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/remove-item-from-array-by-object-property-javascript

PS: Make sure you check other JavaScript tutorials, e.g. how to create an array of numbers in JavaScript or generate an array of years in JavaScript.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment