iT邦幫忙

2023 iThome 鐵人賽

DAY 27
0
Software Development

LELECOCODE 每一天系列 第 27

Day 27: Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 27: 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.

var compactObject = function(obj) {
    
};

Example 1:
Input: obj = [null, 0, false, 1]
Output: [1]

Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}

Example 3:
Input: obj = [null, 0, 5, [0], [false, 16]]
Output: [5, [], [16]]


調用了遞迴,但速度很慢

var compactObject = function(obj) {
    const result = Array.isArray(obj) ? [] : {};

    for (let key in obj) {
        let val = obj[key];
        if (val) {
            if (typeof val === 'object') {
                val = compactObject(val);
            }
            Array.isArray(obj) ? result.push(val) : result[key] = val;
        }
    }
    return result;
};


//Runtime  96ms
//Beats 27.49%of users with JavaScript

//Memory  58.03MB
//Beats 12.53%of users with JavaScript

上一篇
Day 26: Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 28 : Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言