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);
  }
}

1 Answer 1

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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.