Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Group By Property

Data Structures, Operators & Stringsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 118: Enhanced Object Literals

Implement `groupBy(arr, key)` returning an object that groups the items by the value of `item[key]`.

Sample tests

Input: groupBy([{"type":"a","v":1},{"type":"b","v":2},{"type":"a","v":3}], "type")
Output: {"a":[{"type":"a","v":1},{"type":"a","v":3}],"b":[{"type":"b","v":2}]}
Input: groupBy([], "k")
Output: {}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting to initialize the group array before pushing.

Learning resources

  • MDN: Object
Approach & explanation (try first)

Iterating once and pushing each item into a group keyed by item[key] produces a map of arrays.

Loading...
⌘/Ctrl + Enter

Run your code to see results.