FrontendPro

9Implement groupBy() for an array of objects

easyAbout 15 minutesCodingarraysobjectshash-map

Problem

Implement groupBy(items, iteratee). It returns an object whose keys are group names and whose values are arrays of the items in that group, in their original order.

iteratee is either a property name or a function (item, index) => key.

const people = [
  { name: "Asha", team: "web" },
  { name: "Ravi", team: "infra" },
  { name: "Meera", team: "web" },
];
groupBy(people, "team");
// { web: [Asha, Meera], infra: [Ravi] }

groupBy([1.2, 1.8, 2.1], Math.floor);
// { "1": [1.2, 1.8], "2": [2.1] }

Requirements

  • Keep the original order inside each group.
  • Accept any iterable, such as an array or a Set.
  • A key like "__proto__" or "toString" must be an ordinary group.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

Turn a property name into a function: (item) => item[iteratee]. Then the loop only deals with one shape.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever