reduce array by key in javascript

To reduce an array by key in javascript, you can use the reduce() method along with Object.keys() to group the items. Here is an example:

index.tsx
const array = [
  { id: 1, value: 10 },
  { id: 2, value: 20 },
  { id: 1, value: 30 },
  { id: 3, value: 40 },
  { id: 2, value: 50 }
];

const reducedArray = Object.values(array.reduce((acc, obj) => {
  const key = obj.id;
  if (!acc[key]) {
    acc[key] = { id: obj.id, value: obj.value };
  } else {
    acc[key].value += obj.value;
  }
  return acc;
}, {}));

console.log(reducedArray);

// Output:
// [
//   { id: 1, value: 40 },
//   { id: 2, value: 70 },
//   { id: 3, value: 40 }
// ]
494 chars
27 lines

In this example, we start by defining the original array that we want to reduce. We then call the reduce() method on the array, passing in a callback function to handle the reduction.

The callback function takes two parameters: an accumulator object and the current element of the array. In our case, the accumulator object will be a map of keys to their corresponding reduced objects, and the current element will be each individual item in the original array.

We start by extracting the id property from the current element, which will serve as our key for grouping the items. We then check if the accumulator already has an entry for this key. If not, we create a new entry with the id and value of the current element. If there is already an entry, we simply add the value of the current element to the existing value.

Finally, we use Object.values() to convert the resulting map into an array of objects, which is the desired reduced output.

gistlibby LogSnag