{ "data": { "question": { "questionId": "2742", "questionFrontendId": "2631", "boundTopicId": null, "title": "Group By", "titleSlug": "group-by", "content": "
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 with 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.
\n\nPlease solve it without lodash's _.groupBy
function.
\n
Example 1:
\n\n\nInput: \narray = [\n {"id":"1"},\n {"id":"1"},\n {"id":"2"}\n], \nfn = function (item) { \n return item.id; \n}\nOutput: \n{ \n "1": [{"id": "1"}, {"id": "1"}], \n "2": [{"id": "2"}] \n}\nExplanation:\nOutput is from array.groupBy(fn).\nThe selector function gets the "id" out of each item in the array.\nThere are two objects with an "id" of 1. Both of those objects are put in the first array.\nThere is one object with an "id" of 2. That object is put in the second array.\n\n\n
Example 2:
\n\n\nInput: \narray = [\n [1, 2, 3],\n [1, 3, 5],\n [1, 5, 9]\n]\nfn = function (list) { \n return String(list[0]); \n}\nOutput: \n{ \n "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] \n}\nExplanation:\nThe array can be of any type. In this case, the selector function defines the key as being the first element in the array. \nAll the arrays have 1 as their first element so they are grouped together.\n{\n "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]]\n}\n\n\n
Example 3:
\n\n\nInput: \narray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nfn = function (n) { \n return String(n > 5);\n}\nOutput:\n{\n "true": [6, 7, 8, 9, 10],\n "false": [1, 2, 3, 4, 5]\n}\nExplanation:\nThe selector function splits the array by whether each number is greater than 5.\n\n\n
\n
Constraints:
\n\n0 <= array.length <= 105
fn
returns a stringNode.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.
\"], \"typescript\": [\"Typescript\", \"TypeScript 5.1.6, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2022 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }