0

I have 2 arrays like

let arr1 = [
  {id:1, name:'hhj'},
  {id:12, name:'ghdgj'},
  {id:5, name:'gd'}
  ]

let arr2 = [
{id:1, addr:'fsfhg'},
{id:8,addr:'rgdh},
{id:5, name:'gd'}
]

I want a resultant array by comparing two arrays id like,

resultarr =[{id:1, name:'hhj'}
   {id:5, name:'gd'}]

let names=[hhj,gd]

I want this names in seperate array

3
  • 1
    Does this answer your question? How to compare arrays in JavaScript? Commented Aug 23, 2022 at 11:39
  • Not much. It only returns boolean Commented Aug 23, 2022 at 11:40
  • Ok but the essence remains the same. This thread is more focused with your use-case. Commented Aug 23, 2022 at 11:45

2 Answers 2

1

If you want to obtain the objects whose id is in both arrays, you could do this:

let result = array1.filter(el1 => array2.some(el2 => o1.id === el2.id));
Sign up to request clarification or add additional context in comments.

2 Comments

I udated my question.Can you please check it?
You can use the Array.map function to return only the names of the elements of the resulting list like let names = array.map(elem => elem.name)
0

your expected result is incorrectresultarr =[{{id:1, name:'hhj'}}]

in the first object you must set property like

resultarr =[{foo: {id:1, name:'hhj'}}]

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.