To sum items in an array by key in JavaScript, you can use the reduce
method. Here is an example implementation:
index.tsx299 chars15 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
.
gistlibby LogSnag