Home > Web Front-end > JS Tutorial > How to Sum Object Property Values with Shared Keys in JavaScript?

How to Sum Object Property Values with Shared Keys in JavaScript?

Mary-Kate Olsen
Release: 2024-12-14 17:18:18
Original
254 people have browsed it

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

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

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

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!

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