User Tools

Site Tools


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

Using reduce to group people by age

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.

group-people-by-age-reduce.js
function groupPeople(people) {
 
    if (people !== null && Array.isArray(people) && Array(people).length !== 0 && typeof people[0] === 'object') {
 
        let groupedPeopleByAge = people.reduce((group, person) => {
            const { age } = person; //destructuring
            group[age] = group[age] ?? []; //nullish coalescing operatorn
            group[age].push(person.name);
            return group;
        }, {});
 
        return groupedPeopleByAge;
    }
    return [];
}
 
let people = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 25 },
    { name: "Charlie", age: 30 },
    { name: "David", age: 30 },
    { name: "Eve", age: 25 }
];
 
let groupedPeopleByAge = groupPeople(people);
console.log(groupedPeopleByAge);

Output:

{ '25': [ 'Alice', 'Bob', 'Eve' ], '30': [ 'Charlie', 'David' ] }
java-script/reduce/group-people-by-age.txt · Last modified: 2023/08/07 20:42 by odefta