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

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

Barbara Streisand
Release: 2024-11-17 19:37:01
Original
720 people have browsed it

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);
Copy after login

Output:

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

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!

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