0

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);
  }
}
John
  • 1
  • 13
  • 98
  • 177
sekai_no_suda
  • 413
  • 4
  • 11

1 Answers1

3

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))
DecPK
  • 24,537
  • 6
  • 26
  • 42
Oyeme
  • 11,088
  • 4
  • 42
  • 65