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