Practice Group By
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Group By
Problem Statement
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.
Source: Group By on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
array = [ {"id":"1"}, {"id":"1"}, {"id":"2"} ], fn = function (item) { return item.id; }{ "1": [{"id": "1"}, {"id": "1"}], "2": [{"id": "2"}] }# Example 2
array = [ [1, 2, 3], [1, 3, 5], [1, 5, 9] ] fn = function (list) { return String(list[0]); }{ "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] }# Example 3
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] fn = function (n) { return String(n > 5); }{ "true": [6, 7, 8, 9, 10], "false": [1, 2, 3, 4, 5] }Constraints
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.