最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the depth of a tree data structure in a simpler way - Stack Overflow

programmeradmin1浏览0评论

I have a JSON-like hierarchy of JS objects in the following format:

[
  {
    subs: [ ...other objects... ]
  },
  ...other objects...
]

I wrote a method that returns the number of levels of such a hierarchy:

/* Returns the depth of the tree. */
public getDepth(): number {

  function f(obj: object): number {
    let depth = 0;
    if (obj['subs'].length > 0) {
      obj['subs'].forEach((s: object) => {
        const tempDepth = f(s);
        if (tempDepth > depth) depth = tempDepth;
      });
    }
    return depth + 1;
  }

  if (this.tree.length > 0)
    return Math.max(...this.tree.map((s: object) => f(s)));
  else return 0;

}

It works but it's too plicated. Then, I've found this, much cleaner code:

The only difference is that I have not one base object but an array of objects as root. How could I simplify the code to spare that extra if and iteration?

Example data:

const data1 = []; // depth: 0

const data2 = [{}, {}, {}]; // depth: 1

const data3 = [{}, // depth: 5
  {
    "subs": [{
      "subs": [{
        "subs": [{}]
      }, {
        "subs": [{
          "subs": [{}]
        }]
      }]
    }, {
      "subs": [{
        "subs": [{}]
      }]
    }]
  },
  {}
];

I have a JSON-like hierarchy of JS objects in the following format:

[
  {
    subs: [ ...other objects... ]
  },
  ...other objects...
]

I wrote a method that returns the number of levels of such a hierarchy:

/* Returns the depth of the tree. */
public getDepth(): number {

  function f(obj: object): number {
    let depth = 0;
    if (obj['subs'].length > 0) {
      obj['subs'].forEach((s: object) => {
        const tempDepth = f(s);
        if (tempDepth > depth) depth = tempDepth;
      });
    }
    return depth + 1;
  }

  if (this.tree.length > 0)
    return Math.max(...this.tree.map((s: object) => f(s)));
  else return 0;

}

It works but it's too plicated. Then, I've found this, much cleaner code: https://stackoverflow./a/16075976/5214911

The only difference is that I have not one base object but an array of objects as root. How could I simplify the code to spare that extra if and iteration?

Example data:

const data1 = []; // depth: 0

const data2 = [{}, {}, {}]; // depth: 1

const data3 = [{}, // depth: 5
  {
    "subs": [{
      "subs": [{
        "subs": [{}]
      }, {
        "subs": [{
          "subs": [{}]
        }]
      }]
    }, {
      "subs": [{
        "subs": [{}]
      }]
    }]
  },
  {}
];
Share Improve this question edited Mar 14, 2019 at 14:52 tom asked Mar 14, 2019 at 14:26 tomtom 2,3572 gold badges31 silver badges56 bronze badges 1
  • Can you please give the real example input? – Maheer Ali Commented Mar 14, 2019 at 14:44
Add a ment  | 

2 Answers 2

Reset to default 9

You could map the depth of every children and take the maximum value of it.

function getDepth(array) {
    return 1 + Math.max(0, ...array.map(({ subs = [] }) => getDepth(subs)));
}

const
    data1 = [],
    data2 = [{}, {}, {}],
    data3 = [{}, { subs: [{ subs: [{ subs: [{}] }, { subs: [{ subs: [{}] }] }] }, { subs: [{ subs: [{}] }] }] }, {}];

console.log(getDepth(data1) - 1); // 0
console.log(getDepth(data2) - 1); // 1
console.log(getDepth(data3) - 1); // 5

Use Array.prototype.map() to change each item of array to its length and then use Math.max() on array

getDepth = function (obj) {
    var depth = 0;
    if (obj.children) {
        obj.children.forEach(function (d) {
            var tmpDepth = getDepth(d)
            if (tmpDepth > depth) {
                depth = tmpDepth
            }
        })
    }
    return 1 + depth
}
let arr = [...];
let depths = arr.map(x => getDepth(x))
let maxDepth = Math.max(...depths)
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>