some scenarios require us to group objects if a certain property of those objects match. the following js function using the reduce
method mimics this behaviour.
function groupBy(list, field) {
const groups = list.reduce((groups, item) => {
const group = (groups[item[field]] || []);
group.push(item);
groups[item[field]] = group;
return groups;
}, []);
return Object.keys(groups).map(key => groups[key]);
}
usage:
const objects = [{
id: 'some'
},
{
id: 'other'
},
{
id: 'some'
}];
const grouped = groupBy(objects, 'id');
the above will give you an array of arrays:
[
[
{
id: 'some'
},
{
id: 'some'
},
],
[
{
id: 'other'
}
]
]