Array GroupBy Extension
In this lab, you will create an extension of the Array
object so that you can call a groupBy
function on any array. The function will take a callback fn
as a parameter and return a grouped object version of the array. The callback, when applied to each element of the array, will generate a key within the grouped object. The values within the grouped object will be arrays containing all elements from the original array that share the same key.
Arrays of any data type can be grouped using the groupBy
function you'll be building. Keep in mind that the provided callback function fn
needs to return a string key for each element in the array. The order of the values inside the grouped object should be the same order the keys appear in the array. Any key order is acceptable.
Use ESM import/export for your code.
Please avoid using lodash's _.groupBy
to solve this problem.
Examples
Example 1
Input:
array = [ { "id": "1" }, { "id": "1" }, { "id": "2" } ]; fn = function (item) { return item.id; };
Output:
{ "1": [{ "id": "1" }, { "id": "1" }], "2": [{ "id": "2" }] }
Example 2
Input:
array = [ [1, 2, 3], [1, 3, 5], [1, 5, 9] ]; fn = function (list) { return String(list[0]); };
Output:
{ "1": [ [1, 2, 3], [1, 3, 5], [1, 5, 9] ] }
Example 3
Input:
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; fn = function (n) { return String(n > 5); };
Output:
{ "true": [6, 7, 8, 9, 10], "false": [1, 2, 3, 4, 5] }
Constraints
0 <= array.length <= 105
fn
returns a string key