Home >Web Front-end >JS Tutorial >How to Group and Sum an Array of Objects by Property Using jQuery?

How to Group and Sum an Array of Objects by Property Using jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 19:37:01782browse

How to Group and Sum an Array of Objects by Property Using jQuery?

How to Group and Sum an Array of Objects by Property Using jQuery

jQuery provides powerful methods for data manipulation, including the ability to group arrays of objects by common properties and sum their associated values.

Solution

To achieve this grouping and summation with jQuery:

  1. Iterate over the array of objects using the .each() method.
  2. For each object, check if the Id property already exists in the result array.
  3. If it exists, increment the corresponding qty value by the object's qty value.
  4. Otherwise, create a new object in the result array with the Id property and a qty value equal to the object's qty value.

Example Code

var array = [
  { Id: "001", qty: 1 },
  { Id: "002", qty: 2 },
  { Id: "001", qty: 2 },
  { Id: "003", qty: 4 }
];

var result = [];
$.each(array, function(index, object) {
  if (!$.inArray(object.Id, result)) {
    result.push({ Id: object.Id, qty: 0 });
  }
  $.grep(result, function(value) {
    if (value.Id === object.Id) {
      value.qty += object.qty;
    }
  });
});

console.log(result);

Output:

[
  { Id: "001", qty: 3 },
  { Id: "002", qty: 2 },
  { Id: "003", qty: 4 }
]

The above is the detailed content of How to Group and Sum an Array of Objects by Property Using jQuery?. 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
Previous article:Math.ceil vs Math.floorNext article:Math.ceil vs Math.floor