昨天因為一些事情搞到咖啡廳回來後都沒看書,今天開始真的要認真了。
Day23: Group By
問題描述:
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.
Please solve it without lodash’s _.groupBy function.
問題難度:Medium
問題限制:
0 <= array.length <= 105fnreturns a string
我的解題過程:
題目的要求是說:當我們使用這個method時,回傳一個array,這個array 裡面會是一個object,他的key會是fn(arr[i]) 的輸出,而value則是擁有這個輸出的array。
 fn 的回傳會是字串。
所以首先我們先宣告一個空的object,並且用for迴圈把整個array遍歷一次:
1  | const ans = {}  | 
在code裡面就是這次的關鍵,我們要確認在我們的ans裡面有沒有這個key,因此要使用hasOwnProperty 這個內建的method,因此結果會變成:
1  | if (ans.hasOwnProperty(fn(this[i]))) {  | 
fn(this[i])重複太多次,因此我們用變數把它裝起來:
1  | const key = fn(this[i])  | 
最後在return ans就可以了!
我的code:
1  | Array.prototype.groupBy = function(fn) {  | 
其他解法:
1  | Array.prototype.groupBy = function(fn) {  | 
結論:
這次的題目稍為卡在如何去判斷這組array有沒有這個key,去google了一下發現了可以使用hasOwnProperty()來做處理,當知道了這個方法後,一切問題都解決了!