Home >Web Front-end >JS Tutorial >How to Sum Values of Duplicate Keys in a JavaScript Array of Objects?

How to Sum Values of Duplicate Keys in a JavaScript Array of Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 07:41:24435browse

How to Sum Values of Duplicate Keys in a JavaScript Array of Objects?

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:&quot;Mon Sep 23 2013 00:00:00 GMT-0400&quot;, val:54} // <- duplicate key
]

Our goal is to obtain an array with unique keys and summed values, like this:

reducedObjArr = [
    {key:&quot;Mon Sep 23 2013 00:00:00 GMT-0400&quot;, val:96},
    {key:&quot;Mon Sep 24 2013 00:00:00 GMT-0400&quot;, val:78},
    {key:&quot;Mon Sep 25 2013 00:00:00 GMT-0400&quot;, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn