xxxxxxxxxx
const groupBy = (arr, groupFn) =>
arr.reduce(
(grouped, obj) => ({
grouped,
[groupFn(obj)]: [ (grouped[groupFn(obj)] || []), obj],
}),
{}
);
const people = [
{ name: 'Matt' },
{ name: 'Sam' },
{ name: 'John' },
{ name: 'Mac' },
];
const groupedByNameLength = groupBy(people, (person) => person.name.length);
/**
{
'3': [ { name: 'Sam' }, { name: 'Mac' } ],
'4': [ { name: 'Matt' }, { name: 'John' } ]
}
*/
console.log(groupedByNameLength);
xxxxxxxxxx
function groupArrayOfObjects(list, key) {
return list.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);//will be the Males
console.log(groupedPeople.Female);//will be the Females
xxxxxxxxxx
const groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, {}); // empty object is the initial value for result object
};
xxxxxxxxxx
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {"3": ["one", "two"], "5": ["three"]}
Run code snippet
xxxxxxxxxx
var cars = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {'make': 'kia', 'model': 'optima', 'year': '2012'},
];
result = cars.reduce((h, car) => Object.assign(h, { [car.make]:( h[car.make] || [] ).concat({model: car.model, year: car.year}) }), {})
console.log(JSON.stringify(result));