-1

From the given array of objects how to filter the expected output

let a = [{name:'Hari',age:2},{name:'Chana',age:4},{name:'Like',age:5}]
let b = [{name:'Chana',age:14},{name:'Like',age:15}];

I tried this but not working;

let c =a.filter(elm => b.find(el => el.name === elm.name));

expected output is [{name:'Hari',age:2}]

Rijo
  • 2,963
  • 5
  • 35
  • 62
  • 2
    You need to flip your condition, so `!b.find(...)`. But I wouldn't use `.find()` here as you're after a boolean, instead, you could use `!b.some(...)` – Nick Parsons Feb 03 '23 at 12:07

2 Answers2

3

You need to change little modification inside code of filter and final code will be :

let a = [{name:'Hari',age:2},{name:'Chana',age:4},{name:'Like',age:5}]
let b = [{name:'Chana',age:14},{name:'Like',age:15}];
    
let c = a.filter(elm => !b.find(el => el.name === elm.name));
console.log(c);

Result will be:

[ { name: 'Hari', age: 2 } ]
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
2

Check if the result of filter === 0

let a = [{name:'Hari',age:2},{name:'Chana',age:4},{name:'Like',age:5}]
let b = [{name:'Chana',age:14},{name:'Like',age:15}];

let c = a.filter(x => b.filter(y => y.name === x.name).length === 0);
console.log(c);
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Not that it really matters because the arrays are small in this example, but `b.filter()` needs to go through the entire array, by keeping `.find()` or using something like `.every()` or `.some()` instead (which all exit early), you can avoid looping the entire array if you find a matching name earlier on in `b` – Nick Parsons Feb 03 '23 at 12:10