Consider the following array of objects:
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}, //Our goal is to merge duplicate keys and sum their respective values, resulting in:
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} ]While an initial attempt might involve iterating and pushing values, a more efficient approach involves leveraging JavaScript's built-in functions:
// Use a Map to count values with the same key const 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 of objects const reducedObjArr = [...counts].map(([key, value]) => { return {key, value}; });This method reduces the array to a Map where keys represent duplicate key values and values represent their sums. The Map is then converted back to an array of objects for readability.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3