Combining Same-Key Property Values in an Array of Objects
Given an array of JavaScript objects like the one below, how can we combine duplicate keys by summing their corresponding values?
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 ]
Our goal is to obtain an array with unique keys and summed values, like this:
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} ]
Solution Using Map and Reduce
Instead of iterating and pushing values, we can utilize the powerful combination of map and reduce:
const 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 ]; // Convert data into a Map with reduce const counts = objArr.reduce((prev, curr) => { const count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map()); // Map counts object back to an array const reducedObjArr = [...counts].map(([key, value]) => { return {key, value} }); console.log(reducedObjArr);
This approach effectively aggregates and combines values with the same keys, resulting in the desired reduced array.
The above is the detailed content of How to Sum Values of Duplicate Keys in a JavaScript Array of Objects?. For more information, please follow other related articles on the PHP Chinese website!