我如何递归地找到深度嵌套对象数组中的最高数字

问题描述 投票:0回答:0

给定这个深度嵌套的对象数组。我要找最高评论id

    const comments = [
  {
    id: 1,
    text: "First comment!",
    parentId: null,
    comments: [
      {
        id: 2,
        text: "Reply to comment 1",
        parentId: 1,
        comments: []
      },
      {
        id: 3,
        text: "Another reply to comment 1",
        parentId: 1,
        comments: [ ]
      }
    ]
  },
  {
    id: 5,
    text: "Second comment!",
    parentId: null,
    comments: [
      {
        id: 6,
        text: "Reply to comment 5",
        parentId: 5,
        comments: []
      },
    ]
  },
];

这是我试过的

const getGreatest = (arr, greatest = -Infinity) => {
  for (let i = 0; i < arr.length; i++) {
    let comment = arr[i];
    if (Array.isArray(comment.comments) && comment.comments.length > 0) {
       greatest = Math.max(greatest , comment.id)
        getGreatest(comment.comments, greatest);
    }
  }
  return greatest; //returns 5
};

我知道另一种方法是展平对象数组然后找到最大的数字但是如果我想在递归中这样做,我该怎么做?

非常感谢。

javascript arrays recursion depth-first-search
© www.soinside.com 2019 - 2024. All rights reserved.