AniUI Academy

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 1 and the string "1" end up in the same bucket.
Asked atMetaNetflixStripe

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.