-1

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 },
];
0

1 Answer 1

-1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It is the shortest implementation I have been able to come up with.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.