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.
寫一個程式碼來強調所有的陣列中,以便您你可以呼叫 array.groupBy(fn) 模型,並回傳該陣列的分群結果。
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.
分組陣列是一物件,其中每一個 key 是 fn(arr[i]) 的結果,每一個 value 是原始陣列中具有該項目的陣列。 提供的呼叫函式 fn 將接受陣列中的項目並回傳一個字串的 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.
每個 value 的列表中順序應該是項目在陣列中出現的順序。任何鍵的順序都是可以接受的。 請在不使用 lodash 的 _.groupBy 函式的情況下解決此問題。
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] }
solution:
運用 JavaScript中的 Array.prototype 來建立一個 groupBy 的函式:
首先依據題目需求建立對應需回傳的 {} 叫做 group,
運用 for of 來遍歷 array 中的每個 element,
並宣告變數 key 為 element 經過 fn 函式處理好的結果。
接著,檢查 group 物件中是否存在該陣列的 key,
– 如果有,則將該元素推入對應的陣列中。
– 如果沒有,則建立一個新的陣列,將該元素作為值傳入。
當迭代完陣列中所有的元素後,回傳最後的 group 物件。
Code 1: BigO(1)
Array.prototype.groupBy = function(fn) { const group = {} for (const element of this) { const key = fn(element) if (group[key]) { group[key].push(element) } else { group[key] = [element] } } return group; };
FlowChart:
Example 1
array = [ {"id":"1"}, {"id":"1"}, {"id":"2"} ] const fn = function (item) { return item.id; } console.log(array.groupBy(fn)) { '1': [ { id: '1' } ] } { '1': [ { id: '1' }, { id: '1' } ] } { '1': [ { id: '1' }, { id: '1' } ], '2': [ { id: '2' } ] }
Example 2
array = [ [1, 2, 3], [1, 3, 5], [1, 5, 9] ] const fn = function (list) { return String(list[0]); } console.log(array.groupBy(fn)); { '1': [ [ 1, 2, 3 ] ] } { '1': [ [ 1, 2, 3 ], [ 1, 3, 5 ] ] } { '1': [ [ 1, 2, 3 ], [ 1, 3, 5 ], [ 1, 5, 9 ] ] }
Example 3
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const fn = function (n) { return String(n > 5); } console.log(array.groupBy(fn)) { false: [ 1 ] } { false: [ 1, 2 ] } { false: [ 1, 2, 3 ] } { false: [ 1, 2, 3, 4 ] } { false: [ 1, 2, 3, 4, 5 ] } { false: [ 1, 2, 3, 4, 5 ], true: [ 6 ] } { false: [ 1, 2, 3, 4, 5 ], true: [ 6, 7 ] } { false: [ 1, 2, 3, 4, 5 ], true: [ 6, 7, 8 ] } { false: [ 1, 2, 3, 4, 5 ], true: [ 6, 7, 8, 9 ] } { false: [ 1, 2, 3, 4, 5 ], true: [ 6, 7, 8, 9, 10 ] }