0

Trying to work out the most performant way to merge objects from two arrays (that share an id) into a brand new array of the same length of the original two arrays.

For example:

// Merge these two arrays
const arrayOne = [
  { id: 34560, name: "John" },
  { id: 23123, name: "Jake" },
  { id: 11023, name: "Peter" },
  { id: 29221, name: "Sara" }
];

const arrayTwo = [
  { id: 34560, age: 24 },
  { id: 23123, age: 30 },
  { id: 11023, age: 19 },
  { id: 29221, age: 20 }
];

// Into this array
const merged = [
  { id: 34560, name: "John", age: 24 },
  { id: 23123, name: "Jake", age: 30 },
  { id: 11023, name: "Peter", age: 19 },
  { id: 29221, name: "Sara", age: 20 }
];

This is what I've got so far:

const mergedArray = [];

arrayOne.forEach(x => {
  arrayTwo.forEach(y => {
    if (x.id === y.id) {
      mergedArray.push(Object.assign(x, y));
    }
  })
})

Any help is appreciated. Thanks in advance.

realph
  • 4,481
  • 13
  • 49
  • 104
  • probably a better question on http://codereview.stackexchange.com/ since it is about optimizing working code – charlietfl Dec 18 '16 at 18:44
  • Would be far more performant to iterate one array first and add it's ID to a temporary object as property, then you would only loop the other array once also and check if that id property exists in temp object – charlietfl Dec 18 '16 at 18:46
  • 2
    @Gothdo - at least find something which is an actual duplicate of this question: 1 - http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items, 2 - http://stackoverflow.com/questions/19480008/javascript-merging-objects-by-id – Ori Drori Dec 18 '16 at 18:53
  • 1
    Vanilla js example https://jsfiddle.net/svfam112/ – charlietfl Dec 18 '16 at 19:02
  • @charlietfl Elegant stuff! Submit this as an answer and I'll happily accept it. – realph Dec 22 '16 at 22:08

0 Answers0