Remove a specific object from an object array, filtering by a key and value pair

59 views Asked by At

Is there any quick way to remove a specific object from an object array, filtering by a key and value pair, without specifying an index number?

For example, if there was an object array like so:

const arr = [
  { id: 1, name: 'apple' },
  { id: 2, name: 'banana' },
  { id: 3, name: 'cherry' },
  ...,
  { id: 30, name: 'grape' },
  ...,
  { id: 50, name: 'pineapple' }
]

How can you remove only the fruit which has the id: 30 without using its index number?

I have already figured out one way like the following code, but it looks like a roundabout way:

for ( let i = 0; i < arr.length; i++) {
  if ( arr[i].id === 30 ) {
    arr.splice(i, 1);
  }
}
1

There are 1 answers

0
Oyeme On

with es6 standard, you can use the filter method

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const arr = [
      { id: 1, name: 'apple' },
      { id: 2, name: 'banana' },
      { id: 3, name: 'cherry' },
      { id: 30, name: 'grape' },
      { id: 50, name: 'pineapple' }
    ];    
    // !== for strict checking
    console.log(arr.filter(e => e.id !== 30))