You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过递归获取深度嵌套对象数组中的最大评论ID

如何用递归找到嵌套评论数组中的最大ID?

给定如下深度嵌套的评论对象数组,需要找到最大的comment 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: []
      },
    ]
  },
];

尝试了以下递归函数,但返回结果是5,不符合预期:

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
};

已知可以通过扁平化数组的方式找到最大值,但想了解如何用递归正确实现该功能?


问题分析

你的递归函数存在两个关键错误:

  • 遗漏无嵌套子评论的节点:仅处理了带有子评论的节点,像id=6这类没有子评论的节点,其id完全没参与最大值比较
  • 未接收递归返回值:调用getGreatest(comment.comments, greatest)时,没有将子递归找到的更大值赋值回greatest,导致子层的最大值无法传递到外层

正确的递归实现

方式一:带累加参数的递归

修正逻辑,确保每个节点的id都参与比较,同时接收递归返回值更新最大值:

const getGreatest = (arr, greatest = -Infinity) => {
  for (let i = 0; i < arr.length; i++) {
    const comment = arr[i];
    // 先比较当前节点的id,无论是否有子评论
    greatest = Math.max(greatest, comment.id);
    // 若存在子评论,递归处理并更新最大值
    if (Array.isArray(comment.comments) && comment.comments.length > 0) {
      greatest = getGreatest(comment.comments, greatest);
    }
  }
  return greatest;
};

调用getGreatest(comments)会返回预期的6。

方式二:函数式风格递归

无需累加参数,通过拆分数组元素递归计算最大值,代码更简洁:

const getGreatest = (arr) => {
  // 空数组返回负无穷,作为递归终止条件
  if (arr.length === 0) return -Infinity;
  const [currentComment, ...remainingComments] = arr;
  // 取当前节点id、当前节点子评论的最大值、剩余节点的最大值中的最大者
  return Math.max(
    currentComment.id,
    getGreatest(currentComment.comments),
    getGreatest(remainingComments)
  );
};

这种写法通过递归拆解问题,逐步比较所有层级的节点id,最终得到全局最大值。


内容的提问来源于stack exchange,提问作者desh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:07:44