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

How Can I Group and Sum Objects in an Array by a Specific Property Using jQuery?

Mary-Kate Olsen
Release: 2024-11-17 09:30:03
Original
597 people have browsed it

How Can I Group and Sum Objects in an Array by a Specific Property Using jQuery?

Grouping and Summing Objects in an Array

To group an array of objects by a specific property and sum up another property in jQuery, you can utilize the following steps:

1. Loop and Reduce:
Use the $.each() function to iterate over the array, and for each object, check if an object with the same grouping property already exists in the result array. If not, create a new object with the grouping property and an initial quantity of 0. Add this object to the result array.

2. Sum Up Properties:
Within the loop, add the value of the property you want to sum (e.g., qty) from the current object to the corresponding object in the result array. This effectively accumulates the quantities for each group.

Here's an example code using jQuery:

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

var result = [];
$.each(array, function(i, obj) {
  var idx = result.findIndex(x => x.Id === obj.Id);
  if (idx === -1) {
    result.push({ Id: obj.Id, qty: 0 });
    idx = result.length - 1;
  }
  result[idx].qty += obj.qty;
});

console.log(result);
Copy after login

This code will log the following output:

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

By following these steps, you can effectively group and sum the properties of objects in an array, enabling you to extract valuable insights from your data.

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