Home >Web Front-end >JS Tutorial >How to Sum Values of Identical Keys in an Array of JavaScript Objects?

How to Sum Values of Identical Keys in an Array of JavaScript Objects?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 13:03:10711browse

How to Sum Values of Identical Keys in an Array of JavaScript Objects?

Summing Values of Similar Keys in an Array of Objects

Problem:

Given an array of objects, determine a method to compute the sum (or other mathematical operations) of values associated with objects that share the same key.

Example:

Consider the following array of objects:

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

The desired output would sum the 'value' property for objects with matching 'name' properties, resulting in:

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

Solution:

The solution involves iterating through the input array, aggregating identical key values into a separate object.

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

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

The resulting holder object will contain key-value pairs where the keys are unique name values, and the values are the sum of associated value properties.

{
  'P1': 300,
  'P2': 200,
  'P3': 450
}

To generate the desired output, iterate through the properties of the holder object and create new objects:

var obj2 = [];

for (var prop in holder) {
  obj2.push({ name: prop, value: holder[prop] });
}

The final result, stored in obj2, fulfills the requirements of summing values for objects with similar keys.

The above is the detailed content of How to Sum Values of Identical Keys in an Array of 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