Group By - Problem
Group By Array Enhancement

Your task is to enhance the JavaScript Array prototype by implementing a groupBy(fn) method that can be called on any array. This method should transform the array into a grouped object based on a provided callback function.

How it works:
• The callback function fn takes each array element and returns a string key
• Elements with the same key are grouped together in arrays
• The result is an object where keys are the function outputs and values are arrays of original elements
• The order within each group should match the original array order

Example:
[1, 2, 3].groupBy(x => x > 1 ? 'big' : 'small')
Returns: {'small': [1], 'big': [2, 3]}

Note: You cannot use lodash's _.groupBy function

Input & Output

example_1.js — Basic Even/Odd Grouping
$ Input: arr = [1, 2, 3, 4, 5] fn = x => x % 2 === 0 ? 'even' : 'odd'
Output: {'odd': [1, 3, 5], 'even': [2, 4]}
💡 Note: Elements are grouped by whether they are even or odd. The order within each group matches the original array order.
example_2.js — String Length Grouping
$ Input: arr = ['apple', 'bat', 'car', 'elephant', 'dog'] fn = str => str.length.toString()
Output: {'5': ['apple'], '3': ['bat', 'car', 'dog'], '8': ['elephant']}
💡 Note: Strings are grouped by their length. 'apple' has 5 characters, 'bat', 'car', and 'dog' each have 3 characters, and 'elephant' has 8 characters.
example_3.js — Object Property Grouping
$ Input: arr = [{age: 25, name: 'Alice'}, {age: 30, name: 'Bob'}, {age: 25, name: 'Charlie'}] fn = person => person.age.toString()
Output: {'25': [{age: 25, name: 'Alice'}, {age: 25, name: 'Charlie'}], '30': [{age: 30, name: 'Bob'}]}
💡 Note: Objects are grouped by the 'age' property. Alice and Charlie are both 25, so they're in the same group, while Bob is 30 and in his own group.

Visualization

Tap to expand
📮 Mail Sorting Process (Group By Analogy)Incoming Letters:Letter 1Oak StLetter 2Pine AveLetter 3Oak St📖 Read Addressfn(letter) → street nameO(1) operationMailboxes (Groups):📬 Oak St[Letter 1,Letter 3]📬 Pine Ave[Letter 2]O(1) lookup🚀 Algorithm Steps1. For each letter (array element):• Read address using callback function → get street name (key)• Check if mailbox exists for this street (O(1) hash lookup)• Place letter in existing mailbox OR create new mailboxTime Complexity: O(n)Space Complexity: O(n)
Understanding the Visualization
1
Receive Mail Batch
Start with a collection of letters (array elements) to sort
2
Read Address
For each letter, read the address (apply callback function) to determine destination
3
Find/Create Mailbox
Look for existing mailbox with that street name (hash map lookup) or create new one
4
Place Letter
Put the letter in the appropriate mailbox (add element to group array)
5
Repeat Process
Continue until all letters are sorted into their respective mailboxes
Key Takeaway
🎯 Key Insight: Hash maps provide O(1) average lookup time, making group operations incredibly efficient compared to searching through arrays linearly.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through array, with O(1) hash table operations for key lookup and insertion

n
2n
Linear Growth
Space Complexity
O(n)

Space to store the result object containing all n elements grouped by keys

n
2n
Linearithmic Space

Constraints

  • 1 ≤ array.length ≤ 105
  • The callback function will always return a string
  • Array elements can be of any type (numbers, strings, objects, etc.)
  • The callback function is pure (no side effects)
  • Keys in the result object can be in any order
  • Values within each group must maintain original array order
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
24.6K Views
Medium Frequency
~15 min Avg. Time
892 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