-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}]

1
  • 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(...) Commented Feb 3, 2023 at 12:07

2 Answers 2

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 } ]
Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.