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
Release: 2024-12-08 05:51:09
Original
329 people have browsed it

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
]
Copy after login

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}
]
Copy after login

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};
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template