Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

eliminate a variable for an accumulation operation

The following code produces the desired result but is there a way to refactor it to eliminate the accumulator variable?

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const accumulator = {};

data.forEach(o => {
  accumulator[o.id] = { ...accumulator[o.id] , ...o } || o;
});

console.log(accumulator);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The || o part doesn’t make sense (objects are always truthy), and the repeated spread can become a serious performance trap. It’s also good practice to start with Object.create(null) when using an object as a map to avoid keys colliding with things on Object.prototype (even though it looks like you have numeric keys for the moment).

So, let’s restart from this more efficient and reliable version:

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const accumulator = Object.create(null);

data.forEach(o => {
  Object.assign(accumulator[o.id] ??= {}, o);
});

console.log(accumulator);

With that in mind, here’s how you would use Array.prototype.reduce:

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const accumulator = data.reduce(
  (accumulator, o) => {
    Object.assign(accumulator[o.id] ??= {}, o);
    return accumulator;
  },
  Object.create(null)
);

console.log(accumulator);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading