Group by key in JavaScript
Turns a flat array into an object keyed by whatever you pick out of each item.
function groupBy(items, keyFn) {
const groups = {};
for (const item of items) {
const key = keyFn(item);
if (!groups[key]) groups[key] = [];
groups[key].push(item);
}
return groups;
}
Keywords and builtins used here
constforfunctionifofreturn
The run, in numbers
- Lines
- 9
- Characters to type
- 183
- Tokens
- 61
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 39 seconds.
Step 5 of 8 in Objects & collections, step 31 of 43 in Language basics.