Categories
JavaScript Answers

How to Remove an Object from an Array of Objects in JavaScript?

Spread the love

To remove an object from an array of objects in JavaScript, we can use the JavaScript array’s findIndex method to get the index of the first element that matches the given condition.

Then we can use the JavaScript array’s splice method to remove the item from the list.

For instance, we can write:

const arr = [{
  "value": "14",
  "label": "7"
}, {
  "value": "14",
  "label": "7"
}, {
  "value": "18",
  "label": "7"
}]


const matchesEl = (el) => {
  return el.value === '14' && el.label === '7';
}

arr.splice(arr.findIndex(matchesEl), 1);
console.log(arr)

We have the arr array with the object’s we want to remove.

Then we have the matchesEl fuinction that returns the boolean expression that matches an item where el.value is 14 and el.label is 7.

Next, we call arr.findIndex with matchesEl to return the index of the first object that has value 14 and label 7 in `arr.

Then we call arr.splice with the returned index and 1 to remove that entry from arr.

Therefore, arr is now:

[
  {
    "value": "14",
    "label": "7"
  },
  {
    "value": "18",
    "label": "7"
  }
]

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.