'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
My desired output would be
[ { name: 'Adam', age: 30, country: 'USA' }, { name: 'Bob', age: 40, country: 'China' } ]
Solution 1:[1]
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';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aweimon |
