Home > Web Front-end > JS Tutorial > body text

How to Efficiently Sum Values of Similar Keys in JavaScript Objects?

Barbara Streisand
Release: 2024-11-23 04:17:13
Original
131 people have browsed it

How to Efficiently Sum Values of Similar Keys in JavaScript Objects?

Summing Values of Similar Object Keys

Given an array of JavaScript objects, how can you effectively sum the values associated with similar keys?

Approach

To achieve this, we can employ the following steps:

  1. Create a Holder Object: Iterate through the original array and populate an object, holder, with the name properties as keys. For each key, initialize the value to the corresponding value or add the value to the existing value if the key already exists.
  2. Build a New Array: Once you have the holder object, create a new array, obj2, by iterating over its properties. For each property, create an object with the name key and the sum of the values as the value.

Example

Consider the example array:

var obj = [
  { 'name': 'P1', 'value': 150 },
  { 'name': 'P1', 'value': 150 },
  { 'name': 'P2', 'value': 200 },
  { 'name': 'P3', 'value': 450 }
];
Copy after login

Applying the above approach:

// Create a holder object to sum values for similar names
var holder = {};
obj.forEach(function(d) {
  if (holder.hasOwnProperty(d.name)) {
    holder[d.name] = holder[d.name] + d.value;
  } else {
    holder[d.name] = d.value;
  }
});

// Populate a new array with the summed values
var obj2 = [];
for (var prop in holder) {
  obj2.push({ name: prop, value: holder[prop] });
}

// Output the result
console.log(obj2);
Copy after login

Expected output:

[
  { 'name': 'P1', 'value': 300 },
  { 'name': 'P2', 'value': 200 },
  { 'name': 'P3', 'value': 450 }
]
Copy after login

The above is the detailed content of How to Efficiently Sum Values of Similar Keys in JavaScript Objects?. 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