sum items in array by key in javascript

To sum items in an array by key in JavaScript, you can use the reduce method. Here is an example implementation:

index.tsx
const arr = [
  {key: 'a', value: 2},
  {key: 'b', value: 3},
  {key: 'a', value: 1},
  {key: 'c', value: 4}
];

const sumByKey = arr.reduce((acc, obj) => {
  const {key, value} = obj;
  acc[key] = (acc[key] || 0) + value;
  return acc;
}, {});

console.log(sumByKey); // Output: {a: 3, b: 3, c: 4}
299 chars
15 lines

In this example, we have an array of objects where each object has a key and a value property. We want to sum the value for each unique key in the array.

We use the reduce method with an initial empty object as the accumulator. For each object in the array, we destructure the key and value properties and use them to update the accumulator object.

If the key exists in the accumulator object, we add the value to the existing sum. If not, we set the sum to the value.

Finally, we return the updated accumulator object which contains the sums for each unique key.

related categories

gistlibby LogSnag