0

I have two arrays as input (array1 & array2) for which I want to check if there is a match on id. If there is a match they should be included in a new array called result.

array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
    
array2 = [
{ id: 279482, stock: 9 }, 
{ id: 31231, stock: 2 }, 
{ id: 330120, stock: 2 }
];

result [
{ x_id:6711230070958, id: 279482, stock: 9 },
{ x_id:6753301168302, id: 330120, stock: 2 }
]

For finding the matches I tried using a filter with includes. Anybody some thoughts on this?

Test Test
  • 1
  • 2
  • Most of the thoughts I have on this come from answers on this site. Perhaps you could could [edit] your question to show what research you've done and any attempts you've made based on that research? – Heretic Monkey May 26 '21 at 13:09

2 Answers2

0

Try this

array1 = [
    { x_id:6711230070958, id:279482 },
    { x_id:6770878283950, id:213 },
    { x_id:6753301168302, id:330120 }
];
    
array2 = [
    { id: 279482, stock: 9 }, 
    { id: 31231, stock: 2 }, 
    { id: 330120, stock: 2 }
];


let arr3 = array1.map((item, i) => Object.assign({}, item, array2[i]));

console.log(arr3)
hu7sy
  • 983
  • 1
  • 13
  • 47
0

Try this:

array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
    
array2 = [
{ id: 279482, stock: 9 }, 
{ id: 31231, stock: 2 }, 
{ id: 330120, stock: 2 }
];

result = [];

array1.forEach(ele=> {
  let match = array2.find(e => e.id == ele.id);
  if(match)
     result.push(Object.assign({}, ele, match))
})

lone_worrior
  • 232
  • 2
  • 15