← All tasksJavaScript · Junior
groupBy: group elements
Write a function groupBy(array, getKey) that sorts elements into groups. The group key is getKey(item), and the value is an array of elements in their original order.
For example, groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even")) returns { odd: [1, 3], even: [2, 4] }.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (4)
expect(groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even"))).toEqual({ odd: [1, 3], even: [2, 4] });
expect(groupBy(["one", "two", "three"], (s) => s.length)).toEqual({ 3: ["one", "two"], 5: ["three"] });
expect(groupBy([], (x) => x)).toEqual({});
const people = [{ name: "Ann", city: "Kyiv" }, { name: "Bob", city: "Warsaw" }, { name: "Eve", city: "Kyiv" }]; expect(groupBy(people, (p) => p.city).Kyiv.map((p) => p.name)).toEqual(["Ann", "Eve"]);