2

Instead of explaining the problem in words, I've just made a quick visual representation below.

Say I have the following array:

let arr1 = [
  {
    id: 1,
    someKey: someValue
  },
  {
    id: 2,
    someKey: someValue
  },
]

and another array:

let arr2 = [
  {
    id: 1,
    numberOfItems: 10
  },
  {
    id: 2,
    numberOfItems: 20
  },
]

How would I create the following array?

let result = [
  {
    id: 1,
    someKey: someValue,
    numberOfItems: 10
  },
  {
    id: 2,
    someKey: someValue,
    numberOfItems: 10
  },
]

So as you can see, both arrays have the same id value. I want to take numberOfItems: 10 from the second array and place it into the first array under the same id.

Note: the two ids are completely different, have different properties and length. The only similarity is the id

halfer
  • 19,824
  • 17
  • 99
  • 186
cup_of
  • 6,397
  • 9
  • 47
  • 94

2 Answers2

4

You could first create a map with id as key and then combine the objects This would solve the problem in O(n):

let arr1 = [
  {
    id: 1,
    someKey: 3
  },
  {
    id: 2,
    someKey: 6
  },
];

let arr2 = [
  {
    id: 1,
    numberOfItems: 10
  },
  {
    id: 2,
    numberOfItems: 20
  },
];

let arr2Map = arr2.reduce((acc, curr) => {
  acc[curr.id] = curr
  return acc;
}, {});
let combined = arr1.map(d => Object.assign(d, arr2Map[d.id]));
console.log(combined);
slider
  • 12,810
  • 1
  • 26
  • 42
0

let arr1 = [
  {
    id: 1,
    someKey: 3
  },
  {
    id: 2,
    someKey: 6
  },
];

let arr2 = [
  {
    id: 1,
    numberOfItems: 10
  },
  {
    id: 2,
    numberOfItems: 20
  },
];

let idToNumberOfItem = {};
arr2.forEach(({id, numberOfItems})=> idToNumberOfItem[id]=numberOfItems)

arr1.forEach((item)=> item['numberOfItems'] =  idToNumberOfItem[item.id])

console.log(arr1);
Mohammed Ashfaq
  • 3,353
  • 2
  • 15
  • 22