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.
What 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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.