Javascript - How to groupby an array objects in Javascript
Published May 10, 2021In 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
const employee= [
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, '
|
Output:
|
Conclusion: we have learned how to use Javascript groupby fuction with reduce() method.
Article Contributed By :
|
|
|
|
3289 Views |