Home  >  Article  >  Web Front-end  >  How to Efficiently Sum Values of Similar Keys in JavaScript Objects?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 04:17:13132browse

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 }
];

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);

Expected output:

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

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!

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