0

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.

2
  • Show what you tried,those are things that should work if you used then right. Commented Jan 29, 2018 at 4:16
  • Adding the code as requested by Paul - arrayFilter(A,B) { const Result= A.filter((o) => B.indexOf(o.name) !== -1); return Result; } Commented Jan 29, 2018 at 4:22

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

   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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.