Home  >  Article  >  Web Front-end  >  How to Sum the Values of Objects with Identical Keys?

How to Sum the Values of Objects with Identical Keys?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 09:59:10658browse

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

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

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!

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