-1

I have a situation like this:

var first = [
    {'id': 1},
    {'id': 2},
    {'id': 3},
    {'id': 4}
];
var second = [
    {'id': 2},
    {'id': 4}
];

I would like to filter all elements from "first" where the id is inside "second". I am trying something like this:

var result = first.filter((x:any) => second.id.indexOf(x.id) < 0);

I tried with foreach, but it did not work. The result I would like to get is this:

var first = [
    {'id': 2},
    {'id': 4}
];
norbitrial
  • 14,716
  • 7
  • 32
  • 59

1 Answers1

1

You can use .filter() and .some() combination.

Try the following:

const first = [
    {'id': 1},
    {'id': 2},
    {'id': 3},
    {'id': 4}
];

const second = [
    {'id': 2},
    {'id': 4}
];

const result1 = first.filter(e => second.some(s => s.id === e.id));
console.log('includes', result1);

const result2 = first.filter(e => !second.some(s => s.id === e.id));
console.log('not includes', result2);

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59