{ "data": { "question": { "questionId": "2742", "questionFrontendId": "2631", "categoryTitle": "JavaScript", "boundTopicId": 2183694, "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.

\n\n

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.

\n\n

The provided callback fn will accept an item in the array and return a string key.

\n\n

The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.

\n\n

Please solve it without lodash's _.groupBy function.

\n\n

 

\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\n\n", "translatedTitle": "分组", "translatedContent": "

请你编写一段可应用于所有数组的代码,使任何数组调用 array. groupBy(fn) 方法时,它返回对该数组 分组后 的结果。

\n\n

数组 分组 是一个对象,其中的每个键都是 fn(arr[i]) 的输出的一个数组,该数组中含有原数组中具有该键的所有项。

\n\n

提供的回调函数 fn 将接受数组中的项并返回一个字符串类型的键。

\n\n

每个值列表的顺序应该与元素在数组中出现的顺序相同。任何顺序的键都是可以接受的。

\n\n

请在不使用 lodash 的 _.groupBy 函数的前提下解决这个问题。

\n\n

 

\n\n

示例 1:

\n\n
\n输入:\narray = [\n  {\"id\":\"1\"},\n  {\"id\":\"1\"},\n  {\"id\":\"2\"}\n], \nfn = function (item) { \n  return item.id; \n}\n输出:\n{ \n  \"1\": [{\"id\": \"1\"}, {\"id\": \"1\"}],   \n  \"2\": [{\"id\": \"2\"}] \n}\n解释:\n输出来自函数 array.groupBy(fn)。\n分组选择方法是从数组中的每个项中获取 \"id\" 。\n有两个 \"id\" 为 1 的对象。所以将这两个对象都放在第一个数组中。\n有一个 \"id\" 为 2 的对象。所以该对象被放到第二个数组中。\n
\n\n

示例 2:

\n\n
\n输入:\narray = [\n  [1, 2, 3],\n  [1, 3, 5],\n  [1, 5, 9]\n]\nfn = function (list) { \n  return String(list[0]); \n}\n输出:\n{ \n  \"1\": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] \n}\n解释:\n数组可以是任何类型的。在本例中,分组选择方法是将键定义为数组中的第一个元素。\n所有数组的第一个元素都是1,所以它们被组合在一起。\n{\n  \"1\": [[1, 2, 3], [1, 3, 5], [1, 5, 9]]\n}\n
\n\n

示例 3:

\n\n
\n输出:\narray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nfn = function (n) { \n  return String(n > 5);\n}\n输入:\n{\n  \"true\": [6, 7, 8, 9, 10],\n  \"false\": [1, 2, 3, 4, 5]\n}\n解释:\n分组选择方法是根据每个数字是否大于 5 来分割数组。\n
\n\n

 

\n\n

提示:

\n\n\n", "isPaidOnly": false, "difficulty": "Medium", "likes": 3, "dislikes": 0, "isLiked": null, "similarQuestions": "[]", "contributors": [], "langToValidPlayground": "{\"cpp\": true, \"java\": true, \"python\": true, \"python3\": true, \"mysql\": false, \"mssql\": false, \"oraclesql\": false, \"c\": false, \"csharp\": false, \"javascript\": false, \"typescript\": false, \"bash\": false, \"php\": false, \"swift\": false, \"kotlin\": false, \"dart\": false, \"golang\": false, \"ruby\": false, \"scala\": false, \"html\": false, \"pythonml\": false, \"rust\": false, \"racket\": false, \"erlang\": false, \"elixir\": false, \"pythondata\": false, \"react\": false, \"vanillajs\": false, \"postgresql\": false}", "topicTags": [], "companyTagStats": null, "codeSnippets": [ { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {Function} fn\n * @return {Object}\n */\nArray.prototype.groupBy = function(fn) {\n \n};\n\n/**\n * [1,2,3].groupBy(String) // {\"1\":[1],\"2\":[2],\"3\":[3]}\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "declare global {\n interface Array {\n groupBy(fn: (item: T) => string): Record\n }\n}\n\nArray.prototype.groupBy = function(fn) {\n \n}\n\n/**\n * [1,2,3].groupBy(String) // {\"1\":[1],\"2\":[2],\"3\":[3]}\n */", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"3.7K\", \"totalSubmission\": \"4.6K\", \"totalAcceptedRaw\": 3679, \"totalSubmissionRaw\": 4610, \"acRate\": \"79.8%\"}", "hints": [ "First declare an object that will eventually be returned.", "Iterate of each element in the array. You can access the array with the \"this\" keyword.", "The key is fn(arr[i]). If the key already exists on the object, set the value to be an empty array. Then push the value onto the array at the key." ], "solution": null, "status": null, "sampleTestCase": "[{\"id\":\"1\"},{\"id\":\"1\"},{\"id\":\"2\"}]\nfunction (item) { return item.id; }", "metaData": "{\n \"name\": \"groupBy\",\n \"params\": [\n {\n \"name\": \"list\",\n \"type\": \"string\"\n },\n {\n \"type\": \"string\",\n \"name\": \"fn\"\n }\n ],\n \"return\": {\n \"type\": \"string\"\n },\n \"languages\": [\n \"javascript\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "envInfo": "{\"javascript\":[\"JavaScript\",\"

\\u7248\\u672c\\uff1aNode.js 16.13.2<\\/code><\\/p>\\r\\n\\r\\n

\\u60a8\\u7684\\u4ee3\\u7801\\u5728\\u6267\\u884c\\u65f6\\u5c06\\u5e26\\u4e0a --harmony<\\/code> \\u6807\\u8bb0\\u6765\\u5f00\\u542f \\u65b0\\u7248ES6\\u7279\\u6027<\\/a>\\u3002<\\/p>\\r\\n\\r\\n

lodash.js<\\/a> \\u5e93\\u5df2\\u7ecf\\u9ed8\\u8ba4\\u88ab\\u5305\\u542b\\u3002<\\/p>\\r\\n\\r\\n

\\u5982\\u9700\\u4f7f\\u7528\\u961f\\u5217\\/\\u4f18\\u5148\\u961f\\u5217\\uff0c\\u60a8\\u53ef\\u4f7f\\u7528 datastructures-js\\/priority-queue@5.3.0<\\/a> \\u548c datastructures-js\\/queue@4.2.1<\\/a>\\u3002<\\/p>\"],\"typescript\":[\"TypeScript\",\"

TypeScript 5.1.6<\\/p>\\r\\n\\r\\n

Compile Options: --alwaysStrict --strictBindCallApply --strictFunctionTypes --target ES2022<\\/p>\\r\\n\\r\\n

lodash.js<\\/a> \\u5e93\\u5df2\\u7ecf\\u9ed8\\u8ba4\\u88ab\\u5305\\u542b\\u3002<\\/p>\\r\\n\\r\\n

\\u5982\\u9700\\u4f7f\\u7528\\u961f\\u5217\\/\\u4f18\\u5148\\u961f\\u5217\\uff0c\\u60a8\\u53ef\\u4f7f\\u7528 datastructures-js\\/priority-queue@5.3.0<\\/a> \\u548c datastructures-js\\/queue@4.2.1<\\/a>\\u3002<\\/p>\"]}", "book": null, "isSubscribed": false, "isDailyQuestion": false, "dailyRecordStatus": null, "editorType": "CKEDITOR", "ugcQuestionId": null, "style": "LEETCODE", "exampleTestcases": "[{\"id\":\"1\"},{\"id\":\"1\"},{\"id\":\"2\"}]\nfunction (item) { return item.id; }\n[[1,2,3],[1,3,5],[1,5,9]]\nfunction (list) { return String(list[0]); }\n[1,2,3,4,5,6,7,8,9,10]\nfunction (n) { return String(n > 5); }", "__typename": "QuestionNode" } } }