how do you merge two arrays of objects by id and date in javascript?

I’m going to assume since you have the spread operator and Array.find in your example that you can use ES6, which includes for of and Object.values as you see below.

An object and simple looping is used to reduce the amount of times you’re iterating. In your example, for every element in names you’re iterating over last names to find one with the same ID. Not only is that not ideal for performance, but it doesn’t work because every time you’re finding the same element with that ID (the first one with that ID in the array).

const names = [
  { id: "1", name: "a", date: "1604616214" },
  { id: "1", name: "Angel", date: "1604616215" },
  { id: "2", name: "b", date: "2004616214" },
  { id: "2", name: "Karen", date: "2004616215" },
  { id: "3", name: "a", date: "3004616220" },
  { id: "3", name: "Erik", date: "3004616221" },
];
const lastnames = [
  { id: "1", lastname: "a", date: "4004616220" },
  { id: "1", lastname: "Ferguson", date: "4004616221" },
  { id: "2", lastname: "b", date: "5004616220" },
  { id: "2", lastname: "Nixon", date: "5004616221" },
  { id: "3", lastname: "a", date: "6004616222" },
  { id: "3", lastname: "Richard", date: "6004616223" },
];

const profiles = {};

function addToProfiles(arr, profiles) {
  for (let obj of arr) {
    if (obj.id != null) {
      // Inits to an empty object if it's not in the profiles objects
      const profile = profiles[obj.id] || {};
      profiles[obj.id] = { ...profile, ...obj };
    }
  }
}

addToProfiles(names, profiles);
addToProfiles(lastnames, profiles);

const third = Object.values(profiles);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top