Home >Web Front-end >JS Tutorial >How to Sum Object Property Values with Shared Keys in JavaScript?
Summing Object Property Values with Shared Keys in JavaScript
Consider the following JavaScript array of objects:
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 ];
The goal is to merge duplicate keys by summing their corresponding val values, resulting in an array like this:
const 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}, ];
To achieve this, a robust solution employing the reduce and map methods can be utilized:
let counts = objArr.reduce((prev, curr) => { let count = prev.get(curr.key) || 0; prev.set(curr.key, curr.val + count); return prev; }, new Map()); let reducedObjArr = [...counts].map(([key, value]) => { return {key, value}; });
This approach first creates a Map using reduce, where each key represents a unique key from the original array and the corresponding value is the sum of all val values with the same key.
Finally, the map method is invoked on the counts map to convert it back into an array of objects with the desired merged values. The output of this code is the reducedObjArr, which contains the merged and summed values as required.
The above is the detailed content of How to Sum Object Property Values with Shared Keys in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!