Home >Web Front-end >JS Tutorial >How to Efficiently Merge JavaScript Objects with Matching Keys and Sum Their Values?

How to Efficiently Merge JavaScript Objects with Matching Keys and Sum Their Values?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 05:51:09297browse

How to Efficiently Merge JavaScript Objects with Matching Keys and Sum Their Values?

Merging Objects with Matching Properties in JavaScript Arrays

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}, // <- duplicate key
]

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.

The above is the detailed content of How to Efficiently Merge JavaScript Objects with Matching Keys and Sum Their Values?. 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