


How do you group JavaScript objects by multiple properties and sum their values?
Nov 11, 2024 am 03:30 AMGrouping Objects By Multiple Properties and Summing Their Values
In JavaScript, it's common to work with arrays of objects. Sometimes, it's necessary to group these objects by multiple properties while performing calculations on their values, such as summing up specific properties.
Problem Overview
Given an array of objects, we aim to group them based on two properties (shape and color). However, we want to treat objects as duplicates only if their shape and color match. The goal is to sum up the used and instances properties of objects within each group and remove any duplicates.
Expected Result
Using the following sample array:
1 2 3 4 5 6 7 8 9 10 |
|
We expect to obtain an array with four groups:
1 2 3 4 |
|
Solution Using Array#reduce and Object#assign
To achieve this, we can utilize JavaScript's Array#reduce method to iterate over the array of objects. For each object, we construct a unique key by concatenating the shape and color properties. We then use an auxiliary object, helper, to keep track of the grouped objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
If the key does not exist in the helper object, we add a new entry using Object.assign() to create a fresh copy of the current object. We then push this new object into the result array.
If the key already exists in helper, it means we've encountered a duplicate. In this case, we simply increment the used and instances properties of the corresponding object in helper.
Finally, we return the result array, which effectively groups objects by shape and color while summing their values.
The above is the detailed content of How do you group JavaScript objects by multiple properties and sum their values?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins
