Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Group Items for Sectioned Lists

Rendering Listsmedium

Course · Section 17: Modern JavaScript Development: Modules, Tooling, and Functional · Lecture 294: Declarative and Functional JavaScript Principles

To render a list split into sections, group rows by a field first. Implement `groupBy(items, key)` returning an object mapping each distinct value of `item[key]` to an array of the items that have it, preserving input order.

Sample tests

Input: groupBy([{"name":"a","cat":"x"},{"name":"b","cat":"y"},{"name":"c","cat":"x"}], "cat")
Output: {"x":[{"name":"a","cat":"x"},{"name":"c","cat":"x"}],"y":[{"name":"b","cat":"y"}]}
Input: groupBy([], "cat")
Output: {}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Assuming a group array already exists and pushing into undefined throws.
  • Sorting or re-keying the result changes the section order the user expects.

Learning resources

  • React: Rendering Lists
Approach & explanation (try first)

A single reduce builds a map from group value to its members. Lazily initializing each bucket the first time it appears keeps the first-seen ordering, which is what a sectioned list renders.

Loading...
⌘/Ctrl + Enter

Run your code to see results.