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

How to aggregate objects that exist in two array?

if I have two (large) arrays that specify a key and a numeric value

var a = [
  { gtin: 'a1', quantity: 1 },
  { gtin: 'a3', quantity: 1 },
];
var b = [
  { gtin: 'a1', quantity: 1 },
  { gtin: 'a4', quantity: 1 },
];

what is the easiest way to get a single array that sums the quantities?
(Lodash ok, fewest iterations over array preferred)

ie

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

 [
  { gtin: 'a1', quantity: 2 },
  { gtin: 'a3', quantity: 1 },
  { gtin: 'a4', quantity: 1 },
];

>Solution :

You could use a Map to keep track of gtin and its accumulated quantity, and then transform it back to array

const a = [
  { gtin: 'a1', quantity: 1 },
  { gtin: 'a3', quantity: 1 },
];

const b = [
  { gtin: 'a1', quantity: 1 },
  { gtin: 'a4', quantity: 1 },
];

const res = Array.from(
  a
    .concat(b)
    .reduce(
      (map, el) => map.set(el.gtin, (map.get(el.gtin) || 0) + el.quantity),
      new Map()
    )
).map(([gtin, quantity]) => ({ gtin, quantity }));

console.log(res);

References

Map

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