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

Lex V
  • 1,414
  • 4
  • 17
  • 35
  • 1
    Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – nice_dev Aug 23 '22 at 11:39
  • Not much. It only returns boolean – Lex V Aug 23 '22 at 11:40
  • Ok but the essence remains the same. [This thread](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) is more focused with your use-case. – nice_dev Aug 23 '22 at 11:45

2 Answers2

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));
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'}}]