Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day23

昨天因為一些事情搞到咖啡廳回來後都沒看書,今天開始真的要認真了。

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.

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 <= 105
  • fn returns a string

我的解題過程:

題目的要求是說:當我們使用這個method時,回傳一個array,這個array 裡面會是一個object,他的key會是fn(arr[i]) 的輸出,而value則是擁有這個輸出的array。

 fn 的回傳會是字串。

所以首先我們先宣告一個空的object,並且用for迴圈把整個array遍歷一次:

1
2
3
4
const ans = {}
for (let i = 0; i <this.length; i++) {
code
}

在code裡面就是這次的關鍵,我們要確認在我們的ans裡面有沒有這個key,因此要使用hasOwnProperty 這個內建的method,因此結果會變成:

1
2
3
4
5
if (ans.hasOwnProperty(fn(this[i]))) {
ans[fn(this[i])].push(this[i])
} else {
ans[fn(this[i])] = [this[i]];
}

fn(this[i])重複太多次,因此我們用變數把它裝起來:

1
2
3
4
5
6
const key = fn(this[i])
if (ans.hasOwnProperty(key)) {
ans[key].push(this[i])
} else {
ans[key] = [this[i]];
}

最後在return ans就可以了!

我的code:

1
2
3
4
5
6
7
8
9
10
11
12
13
Array.prototype.groupBy = function(fn) {
const ans = {}
for (let i = 0; i <this.length; i++) {
const key = fn(this[i])
if (ans.hasOwnProperty(key)) {
ans[key].push(this[i])
} else {
ans[key] = [this[i]];
}
}

return ans
};

其他解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Array.prototype.groupBy = function(fn) {
// Reduce the array into a single object
return this.reduce((grouped, item) => {
// Apply the provided callback function to get the key
const key = fn(item);

// If the key doesn't exist in the grouped object, create a new array for it
if (!grouped[key]) {
grouped[key] = [];
}

// Push the current item to the array associated with the key
grouped[key].push(item);

// Return the updated grouped object for the next iteration
return grouped;
}, {});
};

結論:

這次的題目稍為卡在如何去判斷這組array有沒有這個key,去google了一下發現了可以使用hasOwnProperty()來做處理,當知道了這個方法後,一切問題都解決了!