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

How to Group and Sum an Array of Objects by a Key in JavaScript?

Susan Sarandon
Release: 2024-11-23 03:33:22
Original
540 people have browsed it

How to Group and Sum an Array of Objects by a Key in JavaScript?

Grouping and Summing an Array of Objects by a Key

In JavaScript, you can group an array of objects by a specific key and sum the values associated with that key using jQuery's powerful tools. Here's how you can achieve this:

var array = [
  { Id: '001', qty: 1 },
  { Id: '002', qty: 2 },
  { Id: '001', qty: 2 },
  { Id: '003', qty: 4 }
];
Copy after login

Looping and Summing

One effective method is to iterate through the array and accumulate the values using the reduce() method. This method takes a callback function that reduces the array to a single value, in this case, an object representing the grouped values.

var result = [];
array.reduce(function (res, value) {
  if (!res[value.Id]) {
    res[value.Id] = { Id: value.Id, qty: 0 };
    result.push(res[value.Id]);
  }
  res[value.Id].qty += value.qty;
  return res;
}, {});
Copy after login

Output:

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

This solution efficiently groups the objects by the Id key and sums the corresponding qty values, resulting in an array of objects with grouped and summed values.

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