Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day27

剩下沒幾天就要結束這個系列了,忽然開始有急迫感,我的side project進度嚴重落後,下個月依照計畫要開始投履歷,但我現在想放的side project還沒用好,只有2個之前為了這個專案練習用的,如果下個月10號前沒用好就只能先放這兩個了。

Day27: Compact Object

問題描述:

Given an object or array obj, return a compact object. A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false.

You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.

問題難度:Medium

問題限制:

  • obj is a valid JSON object
  • 2 <= JSON.stringify(obj).length <= 106

我的解題過程:

有點看不懂什麼是compact object ,只是下一句刪除 falsy 我就看懂了。

因此題目的要求是要我們回傳一個沒有 falsy 的array 或 object(看傳進來的參數是什麼)。

所以我們要做的就是判斷值是不是 falsy ,以及如果array裡還有array要怎麼讓他也執行這個判斷

首先我們先處理判斷式的部分,判斷是array 還是 object ****我們可以用

1
2
3
4
5
6
7
var compactObject = function(obj) {
if (Array.isArray(obj)) {
return true
} else {
return false
}
};

這樣我們就可以分別處理裡面的如果是array的內容:

1
2
3
4
5
6
7
8
9
10
if (Array.isArray(obj)) {
let ansObj = []
for (let i = 0; i < obj.length; i++) {
if (Array.isArray(obj[i])) {
obj[i].map((value) => {
if (value) {
ansObj.push(value)
}
})
}

但在object這裡我就有點卡關了,我的寫法回圈太多了導致整個code可讀性非常差。

只好去看答案跟別人的講解。

當我看到答案在處理array時:

1
if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject);

原來有Array.filter(Boolean)這個語法跟Recursive Function

嚴格說來我的想法沒錯,但技術不足導致整個code非常難以閱讀。

我的code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (Array.isArray(obj)) {
let ansObj = []
for (let i = 0; i < obj.length; i++) {
if (Array.isArray(obj[i])) {
obj[i].map((value) => {
if (value) {
ansObj.push(value)
}
})
} else {
if (obj[i]) {
ansObj.push(obj[i])
}
}
}
return ansObj
} else {
let ansObj = Object.entries(obj)
// 過程太冗長
return ansObj
}
};

其他解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
var compactObject = function(obj) {
if (obj === null) return null
if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject);
if (typeof obj !== "object") return obj;

const compacted = {};
for (const key in obj) {
let value = compactObject(obj[key]);
if (Boolean(value)) compacted[key] = value;
}

return compacted;
};

結論:

今天認識了兩個新的東西:Array.filter(Boolean)這個語法跟Recursive Function
看來後續又要花點時間來了解這兩個東西了。
今天有嚴格按照停損點的時間來執行。