Languages

Javascript - array includes() method opposite

0 points
Asked by:
MindOfMadness3
696

What is the correct way of removing objects that have a certain property?

I can use includes() in the followind way:

const array = [
    { id: 1, name: 'Tom1' },
    { id: 2, name: 'Ann' },
    { id: 3, name: 'Tom2' },
    { id: 4, name: 'Kate' },
];

const result = array.filter((item) => item.name.includes('Tom'));

To get the result:

[ { id: 1, name: 'Tom1' }, { id: 3, name: 'Tom2' } ]

But how can I do the opposite to remove the objects above, keeping everything but them?

1 answer
0 points
Answered by:
MindOfMadness3
696

Just negate the result of the function.

// ONLINE-RUNNER:browser;

const array = [
    { id: 1, name: 'Tom1' },
    { id: 2, name: 'Ann' },
    { id: 3, name: 'Tom2' },
    { id: 4, name: 'Kate' },
];

const result = array.filter((item) => !item.name.includes('Tom'));

console.log(JSON.stringify(result, null, 4)); // [ { id: 2, name: 'Ann' }, { id: 4, name: 'Kate' } ]

 

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Array.prototype.includes() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join