java-script:reduce:group-people-by-age
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| java-script:reduce:group-people-by-age [2023/08/07 17:31] – odefta | java-script:reduce:group-people-by-age [2025/01/02 18:22] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== | + | ====== |
| + | |||
| + | 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> | ||
| function groupPeople(people) { | function groupPeople(people) { | ||
| - | | + | |
| if (people !== null && Array.isArray(people) && Array(people).length !== 0 && typeof people[0] === ' | if (people !== null && Array.isArray(people) && Array(people).length !== 0 && typeof people[0] === ' | ||
| - | //get all possible ages | ||
| let groupedPeopleByAge = people.reduce((group, | let groupedPeopleByAge = people.reduce((group, | ||
| - | const { age } = person; | + | const { age } = person; |
| - | 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; | ||
| Line 29: | Line 32: | ||
| let groupedPeopleByAge = groupPeople(people); | let groupedPeopleByAge = groupPeople(people); | ||
| console.log(groupedPeopleByAge); | console.log(groupedPeopleByAge); | ||
| + | </ | ||
| + | |||
| + | Output: | ||
| + | < | ||
| + | { ' | ||
| </ | </ | ||
java-script/reduce/group-people-by-age.1691429473.txt.gz · Last modified: (external edit)
