Skip to the solution
EasyDSA6 min read

Implement groupBy(array, iteratee) — lodash style

490 views

The problem

Problem, as an interviewer would state it: "Implement groupBy(array, iteratee) — grouping array elements into an object keyed by the result of calling iteratee on each element, matching lodash's own well-known _.groupBy behavior."

Examples:

Code
groupBy([1,2,3,4,5,6], n => n % 2 === 0 ? "even" : "odd");
// { odd: [1,3,5], even: [2,4,6] }

Clarifying questions expected:

  • Should the iteratee support both a real function AND a plain string shortcut (grouping by that property name directly), matching lodash's own dual-input convention?
  • What real, correct order should elements appear in WITHIN each group?
  • What should happen if the iteratee genuinely returns a non-string value, like a number or an object?

Code / implementation expected: Yes — real, direct proof with both a function iteratee and a string-property iteratee, confirming correct grouping and preserved insertion order within each group.

  • object
  • groupBy
  • array

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: groupBy correctly partitions by both a function and a string-property iteratee, preserving original order within each group

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 37 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Invert Object Keys

Continue