Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter object within an array that matches search object in Javascript

I am trying to filter and remove objects that are inside of my array however more objects are getting removed than I am hoping to target

const people = [
  {name: 'Adam', age: 30, country: 'USA'},
  {name: 'Carl', age: 30, country: 'UK'},
  {name: 'Bob', age: 40, country: 'China'},
 ];

const results = people.filter(element => {
  // 👇️ using AND (&&) operator
  return element.age !== 30 && element.name !== 'Carl';
});

console.log(results);

outputs:

[ { name: 'Bob', age: 40, country: 'China' } ]

I am hoping to only remove the object where Carl is found

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My desired output would be

[ { name: 'Adam', age: 30, country: 'USA' }, { name: 'Bob', age: 40, country: 'China' } ]

>Solution :

You need to update the filter condition if you need to remove only 30yo Carls

return !(element.age === 30 && element.name === 'Carl');

which is equal to

return element.age !== 30 || element.name !== 'Carl';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading