Build your own groupBy
Live noweasyArrays & Objects+150 XPLive Challenge
Almost every list you render is grouped by something: orders by status, students by year, commits by author.
Implement groupBy(items, keyFn). It takes an array and a function that returns the grouping key for an item, returning an object mapping each key to the array of items that produced it.
Arguments
itemsArray<T>- The input collection to group.
keyFn(item: T) => string | number- A function that returns the grouping key for each item.
Returns
Record<string, T[]> — An object whose keys are the values returned by keyFn, each mapped to the array of items that produced that key — in original input order.
Examples
const people = [
{ name: "Priya", team: "design" },
{ name: "Marcus", team: "eng" },
{ name: "Yuki", team: "design" },
];
groupBy(people, (p) => p.team);
// {
// design: [{ name: "Priya", ... }, { name: "Yuki", ... }],
// eng: [{ name: "Marcus", ... }],
// }groupBy([1, 2, 3, 4, 5, 6], (n) => (n % 2 === 0 ? "even" : "odd"));
// { odd: [1, 3, 5], even: [2, 4, 6] }Items keep their original order inside each bucket.
What it has to do
- Preserve the original order of items inside each group.
- Handle an empty array by returning an empty object.
- Accept keys that are numbers as well as strings.
- Do not mutate the input array.
Notes
- Object keys are always coerced to strings — a numeric key like
1and the string"1"end up in the same bucket.
Stuck? The javascript course covers everything this challenge needs.
Try it yourself· Edit the code, then press Run
Loading playground...
- 1.groups by the returned key
- 2.keeps the original order inside a group
- 3.returns an empty object for an empty array
- 4.accepts numeric keys
- 5.does not mutate the input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
5 tests · +150 XP
Discussion
Sign in to postSign in to join the conversation.Sign in
No comments yet. Be the first to say something.