Skip to content
JavaScript utilities · Core · about 10 minutes

Group by

Implement groupBy(list, key) without Object.groupBy (the tests remove it). key is a function of the item, or a property name. Return a plain object: its keys are the group names and its values are arrays of the items, in their original order. In the tests, the key 'parity' is a function giving odd or even, and 'length' gives a string's length.

Start from

function groupBy(list, key) {
  // Return a plain object of arrays, one per group.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Turn key into a function first: use it when it is a function, otherwise read that property.

  2. Hint 2

    For each item, create the group's array the first time, then push.

Solution

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
function groupBy(list, key) {
  const pick = typeof key === "function" ? key : (item) => item[key];
  const groups = {};
  for (const item of list) (groups[pick(item)] ??= []).push(item);
  return groups;
}

What an interviewer looks for

Shaping API data for a screen is daily frontend work. Interviewers watch for one pass over the list and for a clean handling of the two kinds of key.