lms
lms

Reputation: 93

javascript how to filter an object array based on another object array

Here is the example, Please help with equivalent javascript code

array A = [{id: 1, name:'cat'},{id:2, name:'dog'},{id:3, name:'tiger'}];

array B = [{name:'cat'},{name:'dog'}];

result

expected = [{id: 1, name:'cat'},{id:2, name:'dog'}];

Need to filter Array A based on names available in array B

Similar to SQL where name in ('cat','dog').

Tried to use array.filter and indexOf !== -1

But not getting the expected result.

Upvotes: 0

Views: 66

Answers (2)

saigowthamr
saigowthamr

Reputation: 554

   const a = [{id: 1, name:'cat'}, {id:2, name:'dog'}, {id:3,    name:'tiger'}];
 const b = [{name:'cat'}, {name:'dog'}];


                    

           
   var res = a.filter((per)=>b.find((x)=>per.name===x.name))
   
   console.log(res)

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97381

As the arrays grow bigger, it's probably better to build a lookup object, but a simple approach using Array.prototype.filter() and Array.prototype.some() could look as follows:

const a = [{id: 1, name:'cat'}, {id:2, name:'dog'}, {id:3, name:'tiger'}];
const b = [{name:'cat'}, {name:'dog'}];

const result = a.filter(x => b.some(y => x.name === y.name));

console.log(result);

Upvotes: 2

Related Questions