User Tools

Site Tools


java-script:reduce:group-people-by-age

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:reduce:group-people-by-age [2023/08/07 20:35] odeftajava-script:reduce:group-people-by-age [2023/08/07 20:42] (current) odefta
Line 1: Line 1:
 ====== Using reduce to group people by age ====== ====== Using reduce to group people by age ======
- 
-;;;**reduce** is a method that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.;;; \\ \\  
  
 In this example, the accumulator starts as an empty object {}, and the function is applied to each person object in the people array. In this example, the accumulator starts as an empty object {}, and the function is applied to each person object in the people array.
 +
 +This function is a neat example of how you can use **reduce** in conjunction with other modern JavaScript features like **destructuring** and the **nullish coalescing operator** to concisely perform a complex transformation on an array.
  
 <code javascript group-people-by-age-reduce.js> <code javascript group-people-by-age-reduce.js>
Line 11: Line 11:
  
         let groupedPeopleByAge = people.reduce((group, person) => {         let groupedPeopleByAge = people.reduce((group, person) => {
-            const { age } = person; +            const { age } = person; //destructuring 
-            group[age] = group[age] ?? [];+            group[age] = group[age] ?? []; //nullish coalescing operatorn
             group[age].push(person.name);             group[age].push(person.name);
             return group;             return group;
java-script/reduce/group-people-by-age.1691429723.txt.gz · Last modified: 2023/08/07 20:35 by odefta