Group Array Items by Key
Group an array of records into a map keyed by one of their fields, a building block for reports, indexes, and bucketed aggregations.
Code
export function groupBy(items, keyFn) {
const groups = new Map();
for (const item of items) {
const key = keyFn(item);
const bucket = groups.get(key);
if (bucket) {
bucket.push(item);
} else {
groups.set(key, [item]);
}
}
return groups;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.