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
Understanding the Visualization
1
Input
Array of items and a grouping function
2
Apply Function
Function generates keys for each item
3
Group
Items with same key go in same group
Key Takeaway
🎯 Key Insight: Use a hash map to group items in a single pass - check if key exists, append to existing array or create new one
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code