Problem Description
Enhance all arrays to include a method array.groupBy(fn)
that returns 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 of all items in the original array that generate that key.
Key Insights
- The
fn
callback function will be used to determine the key for each element in the array. - The output will be an object, where keys are the results of the
fn
function applied to the array elements. - Each value in the object is an array of elements from the original array that correspond to each key.
- The order of elements within each group should reflect their order in the original array.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array, as we need to iterate through the array once.
Space Complexity: O(n), in the worst case, we may store all elements in the output object.
Solution
To solve this problem, we will:
- Create a method
groupBy
that takes a callback functionfn
. - Initialize an empty object to hold the grouped results.
- Iterate through each element of the array, applying the
fn
function to determine the key. - For each key, if it doesn't exist in the object, create an array for that key, then push the current element into that array.
- Finally, return the constructed object.