Group By - Problem

Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array.

A grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array which generate that key.

The provided callback fn will accept an item in the array and return a string key.

The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.

Please solve it without lodash's _.groupBy function.

Input & Output

Example 1 — Group by String Length
$ Input: arr = ["hi", "bye", "yo", "hello"], fn = function(x) { return x.length; }
Output: {"2": ["hi", "yo"], "3": ["bye"], "5": ["hello"]}
💡 Note: Group strings by their length: "hi" and "yo" have length 2, "bye" has length 3, "hello" has length 5
Example 2 — Group by First Character
$ Input: arr = ["apple", "banana", "avocado", "cherry"], fn = function(x) { return x[0]; }
Output: {"a": ["apple", "avocado"], "b": ["banana"], "c": ["cherry"]}
💡 Note: Group by first character: 'a' words together, 'b' words together, 'c' words together
Example 3 — Empty Array
$ Input: arr = [], fn = function(x) { return x; }
Output: {}
💡 Note: Empty array returns empty object since there are no items to group

Constraints

  • 0 ≤ arr.length ≤ 105
  • fn returns a string
  • The callback function will always return a valid string

Visualization

Tap to expand
Group By - Single Pass Hash Map INPUT Input Array: "hi" "bye" "yo" "hello" [0] [1] [2] [3] Grouping Function: fn = (x) => x.length String Lengths: 2 3 2 5 Group by length of each string ALGORITHM STEPS 1 Initialize HashMap result = {} 2 Loop Through Array for each item in arr 3 Compute Key key = fn(item) 4 Add to Group result[key].push(item) Building HashMap: "hi" --> key=2 --> {2:["hi"]} "bye" --> key=3 --> {3:["bye"]} "yo" --> key=2 --> {2:["hi","yo"]} "hello"--> key=5 --> {5:["hello"]} O(n) time complexity FINAL RESULT Grouped Object: "2" : ["hi", "yo"] "3" : ["bye"] "5" : ["hello"] Output: {"2": ["hi","yo"], "3": ["bye"], "5": ["hello"]} OK - Grouped! Key Insight: Use a hash map to group elements in O(n) time. For each element, compute the key using the callback function, then initialize an empty array if the key doesn't exist, and push the element to that key's array. This preserves insertion order within each group as required. TutorialsPoint - Group By | Single Pass Hash Map Approach
Asked in
Google 25 Meta 20 Amazon 18 Microsoft 15
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen