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

2
  • Do both arrays have the same length? The same content? And the same item order? Commented Oct 5, 2018 at 15:32
  • no they are completely different arrays other than the id Commented Oct 5, 2018 at 15:32

2 Answers 2

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

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.