In this javascript example we will learn how to use groupby function in javascript. To groupby an array objects we will use javascript reduce() function. This reduce() function will execute a reducer function on array object elements and return grouped array by key names. Example Output: Conclusion: we have learned how to use Javascript groupby fuction with reduce() method.
const employee= [
{ name: "Employee 1", salary: 15000 },
{ name: "Employee 1", salary: 30009 },
{ name: "Employee 2", salary: 40000 },
{ name: "Employee 2", salary: 70000 }
];
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
// Add object to list for given key's value
acc[key].push(obj);
return acc;
}, {});
}
const groupedPeople = groupBy(employee, '
salary
');
console.log(groupedPeople);
[
"Employee 1" : [
{ name: "Employee 1", salary: 15 },
{ name: "Employee 1", salary: 30 },
],
"Employee 2" : [
{ name: "Employee 2", salary: 45 },
{ name: "Employee 2", salary: 70 }
],
]
Article Contributed By :
|
|
|
|
2486 Views |