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

How to Sum the Values of Objects with Identical Keys?

Mary-Kate Olsen
Release: 2024-11-21 09:59:10
Original
658 people have browsed it

How to Sum the Values of Objects with Identical Keys?

Sum Up Values of Objects with Same Keys

In certain programming scenarios, you may encounter situations where you need to combine the values of multiple objects that share a specific key. For instance, consider an array of objects representing products:

[
    {
        'name': 'Product 1',
        'quantity': 5
    },
    {
        'name': 'Product 1',
        'quantity': 3
    },
    {
        'name': 'Product 2',
        'quantity': 10
    },
    {
        'name': 'Product 3',
        'quantity': 25
    }
]
Copy after login

The task is to sum up the quantity values for products with the same name. This results in a new array where each product has its combined quantity:

[
    {
        'name': 'Product 1',
        'quantity': 8
    },
    {
        'name': 'Product 2',
        'quantity': 10
    },
    {
        'name': 'Product 3',
        'quantity': 25
    }
]
Copy after login

To achieve this, follow these steps:

  1. Iterate through the original array.
  2. For each object, check if its name exists as a property in an intermediary object.
  3. If it does, add the 'quantity' value to the existing property value.
  4. If it doesn't, create a new property with the 'name' as the key and the 'quantity' value as the value.
  5. After iterating through all objects, create a new array.
  6. Iterate through the properties of the intermediary object.
  7. For each property, create a new object with the property name as the name and property value as the quantity.
  8. Push this new object into the new array.

By following these steps, you can effectively sum up the values of objects with the same keys, allowing you to perform mathematical operations on grouped data.

The above is the detailed content of How to Sum the Values of Objects with Identical Keys?. 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