The challenge
Write groupBy(list, getKey) that returns an object where each key is getKey(item) and each value is an array of the items with that key, in their original order.
groupBy(["apple", "avocado", "banana"], (w) => w[0])
// { a: ["apple", "avocado"], b: ["banana"] }
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
groupBy(["apple", "avocado", "banana"], (w) => w[0])gives{ a: ["apple", "avocado"], b: ["banana"] }groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? "even" : "odd"))gives{ odd: [1, 3, 5], even: [2, 4] }groupBy([], (x) => x)gives{}
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
reduce with {} as the starting value works nicely here.
Hint 2
For each item: (groups[key] ??= []).push(item).
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function groupBy(list, getKey) {
return list.reduce((groups, item) => {
const key = getKey(item);
(groups[key] ??= []).push(item);
return groups;
}, {});
}
Learn what you need
This exercise uses what Grade 10: Array Power Tools: map, filter & reduce teaches. Read those notes first if any of it is new.