The most efficient method to group by a key on an array of objects in JavaScript is to use the reduce function.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. It applies a function to each element of an array, accumulating a single result, and returns the final output.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue );
Example:
Javascript
const people = [ { name: 'Lee' , age: 21 },
{ name: 'Ajay' , age: 20 },
{ name: 'Jane' , age: 20 }
]; 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(people, 'age'); console.log(groupedPeople); |
Output
{ '20': [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ], '21': [ { name: 'Lee', age: 21 } ] }
Article Tags :
Recommended Articles