When working with JavaScript arrays of objects, you may encounter duplicate keys that represent similar entities. To consolidate these duplicates and aggregate their corresponding values, you can leverage the following approach:
let 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} ]; // Utilize a Map to consolidate duplicate keys let counts = objArr.reduce((prev, curr) => { let count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map()); // Convert the Map back to an array let reducedObjArr = [...counts].map(([key, value]) => { return {key, value} }) console.log(reducedObjArr);
This solution leverages a Map to accumulate values associated with duplicate keys. It iterates through the original array, extracting the key and value of each object. If the key already exists in the Map, it increments its corresponding value. Finally, it converts the Map back into an array of objects, providing the desired result.
The above is the detailed content of How to Merge Duplicate Keys and Sum Their Values in JavaScript Object Arrays?. For more information, please follow other related articles on the PHP Chinese website!