Summing Values of Duplicate Keys in an Array of Objects
In JavaScript, when dealing with an array of objects, one may encounter the need to merge duplicate keys and sum their associated values. Given an array of objects like:
objArr = [ {key: "Mon Sep 23 2013 00:00:00 GMT-0400", val: 42}, {key: "Mon Sep 24 2013 00:00:00 GMT-0400", val: 78}, {key: "Mon Sep 25 2013 00:00:00 GMT-0400", val: 23}, {key: "Mon Sep 23 2013 00:00:00 GMT-0400", val: 54} // duplicate key ]
One would aim to achieve the following:
reducedObjArr = [ {key: "Mon Sep 23 2013 00:00:00 GMT-0400", val: 96}, {key: "Mon Sep 24 2013 00:00:00 GMT-0400", val: 78}, {key: "Mon Sep 25 2013 00:00:00 GMT-0400", val: 23} ]
Instead of iterating and pushing values, a more efficient approach utilizes Map and Reduce:
let counts = objArr.reduce((prev, curr) => { let count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map());
This creates a Map with keys as object keys and values as summed values. Finally, the Map is converted back to an array with:
let reducedObjArr = [...counts].map(([_, value]) => { return {key, value} })
This approach is more concise and eliminates the risk of errors associated with manual iteration.
The above is the detailed content of How to Efficiently Sum Values of Duplicate Keys in a JavaScript Array of Objects?. For more information, please follow other related articles on the PHP Chinese website!