Group by several keys into a nested object
A report groups people by department, then by level within each department. Chaining groupBy by hand gets ugly fast, and the number of levels is often data-driven.
Implement groupByMany(items, keyFns). keyFns is an array of functions applied in order. Group the items by the first function, then group each of those groups by the second, and so on. The result is a nested plain object whose keys at each level are the string form of the keys that function returned, and whose deepest values are arrays of the original items. Items keep their original relative order inside each array, and each level's keys appear in the order those keys were first encountered. When keyFns is empty, there is nothing to group by, so return a shallow copy of items — the array itself, not an object. When items is empty and keyFns is not, return an empty object. Never modify the input.
Arguments
itemsArray- The input list to group.
keyFnsArray<(item) => any>- The grouping stack. The first function groups the items; each subsequent function groups each previous bucket.
Returns
Object | Array — A nested object one level per key function, with arrays of items at the deepest level. Returns a shallow copy of items when keyFns is empty.
Examples
groupByMany(
[
{ d: "eng", l: "senior", n: 1 },
{ d: "eng", l: "junior", n: 2 },
{ d: "design", l: "senior", n: 3 },
],
[(item) => item.d, (item) => item.l],
);
// {
// eng: { senior: [{ n: 1, ... }], junior: [{ n: 2, ... }] },
// design: { senior: [{ n: 3, ... }] },
// }groupByMany([1, 2, 3], []);
// [1, 2, 3] — no key functions returns a shallow copy of the array itselfWhat it has to do
- Apply the key functions in order, nesting one object per level.
- Hold arrays of the original items at the deepest level.
- Use the string form of each key function's return value as the object key.
- Return a shallow copy of
itemswhenkeyFnsis empty. - Preserve the original item order within each group, and do not mutate the input.
Stuck? The javascript course covers everything this challenge needs.
- 1.nests one object per key function
- 2.behaves like a plain groupBy with one key function
- 3.returns a copy of the array when there are no key functions
- 4.returns an empty object for no items
- 5.stringifies numeric keys
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.