Here is an array of objects that I would like to group based on certain keys (JSON format):
[
{
"name": "john",
"lastName": "doe",
"gender": "male"
},
{
"name": "jane",
"lastName": "doe",
"gender": "female"
},
{
"name": "peter",
"lastName": "dickons",
"gender": "male"
},
{
"name": "eva",
"lastName": "dickons",
"gender": "female"
},
]
To group these objects by their last name, the following code can be used:
const groupByObjectKey = (users: User[], key: string): any => {
return users.reduce((rv: any, x: any) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
const usersGroupedByLastName = groupByObjectKey(
users,
"lastName"
);
If you want to group them not only by last name but also by gender using the same function, you can do so as follows:
const groupByObjectKey = (users, key) => {
return users.reduce((rv, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
let users = [{
"name": "john",
"lastName": "doe",
"gender": "male"
},
{
"name": "jane",
"lastName": "doe",
"gender": "female"
},
{
"name": "peter",
"lastName": "dickons",
"gender": "male"
},
{
"name": "eva",
"lastName": "dickons",
"gender": "female"
},
];
const usersGroupedByLastName = groupByObjectKey(
users,
"lastName"
);
console.log(usersGroupedByLastName);