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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 07:51:03543browse

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

Grouping and Summing an Array of Objects by a Property

Problem

Given an array of objects, your goal is to group them by a specific property, such as Id, and calculate the sum of another property, such as qty, for each group using jQuery.

Example

Consider the following input array:

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

The desired output is:

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

Solution

To group the array by Id and sum the qty values for each group using jQuery, you can employ the following approach:

$(array).groupBy('Id').reduce(function (res, obj) {
  return res + obj.qty;
}, 0);

Here's a breakdown of the solution:

  • jQuery's groupBy Plugin: This plugin groups the array of objects based on the specified property, Id. It returns an object with property keys corresponding to the unique Id values.
  • jQuery's reduce Method: This method iterates through the grouped object and applies the specified callback function to calculate the sum of qty values for each group. In this case, the callback function simply adds each object's qty property to the accumulator.

The above is the detailed content of How to Group and Sum an Array of Objects by a 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