How to group elements of an object in JavaScript?
We can do this using Object.groupBy()
method. This method groups elements of an object according to values returned from a callback function.
Example:
const users = [
{
name:"Sandeep",
age:30
},
{
name:"John",
age:20
},
{
name:"Virat",
age:16
},
{
name:"Lionel",
age:35
}
];
const result = Object.groupBy( users, ( { age } ) => {
return age > 20 ? "adult" : "teen";
} );
console.log( result );