I\'m trying to group the following array with objects:
[ { user_id: 301, alert_id: 199, deal_id: 32243 },
{ user_id: 301, alert_id: 200, deal_id: 32243 },
I would like to contribute a neat typescript ES6 group by.
I am not really sure how to tighten up the return value typing. Some trickery is needed there, but this works rather well for me.
/**
* group the supplied list by a set of keys.
* @param list the list of items to group.
* @param children the key for the array of child items.
* @param components the components to group by.
*/
groupByMultipleFields(
list: T[],
children: string,
...components: K[]): any[] {
var grouping = [...list.reduce((r, o) => {
const key = components.map(_ => `${o[_]}`).join(" :: ");
var keyed = r.get(key) || components.reduce((x, y) => { x[y] = o[y]; return x; }, {});
keyed[children] = keyed[children] || [];
keyed[children].push(o);
return r.set(key, keyed);
}, new Map).values()];
return grouping;
}
You will need to turn on the typescript compiler option "downlevelIteration": true
to allow the new Map
to iterate and return values()
.