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

如何递归统计无限嵌套reaction数组对象的总数量与最大嵌套深度?

现有实现的问题
  • 第一种方法reaction.flat(Infinity).length:flat()仅能展平「数组直接嵌套数组」的结构,而你的嵌套关系是存放在每个reaction对象的reactions属性中,不属于数组直接嵌套,flat根本不会遍历到对象内部的属性,统计结果自然不对。
  • 第二种深度计算方法:存在三个明显问题:1. 逻辑顺序错误,你先判断是否为数组,但实际输入的根节点可能是reaction对象而非数组,且未正确统计当前reaction本身的层级;2. 当reactions为空数组时直接返回0,会丢失当前层的深度计数;3. 空数组调用Math.max(...[])会返回-Infinity,运算后会得到异常结果。
  • 第三种总数计算方法:仅计算了第一层数组的reactions长度,既没有统计当前层本身的reaction数量,也没有递归遍历子reactions里的嵌套内容,只能得到第一层子reaction的总数,深层数据完全没统计到。
正确实现

默认统计规则:所有层级的reaction(包括最外层、嵌套的每一层)都计入总数;最大深度从最外层开始算第一层,逐层累加。

统计总reaction数量

const countTotalReactions = (input) => {
  // 输入为数组则遍历所有元素累加计数
  if (Array.isArray(input)) {
    return input.reduce((sum, item) => sum + countTotalReactions(item), 0)
  }
  // 输入为单个reaction对象,先统计自身1个,再加子reaction的数量
  let count = 1
  if (input.reactions?.length) {
    count += countTotalReactions(input.reactions)
  }
  return count
}

统计最大嵌套深度

const getMaxDepth = (input) => {
  // 输入为数组则取所有元素的最大深度
  if (Array.isArray(input)) {
    if (input.length === 0) return 0
    return Math.max(...input.map(getMaxDepth))
  }
  // 输入为单个reaction对象,当前层算1,再加子reaction的最大深度
  let childMaxDepth = 0
  if (input.reactions?.length) {
    childMaxDepth = getMaxDepth(input.reactions)
  }
  return 1 + childMaxDepth
}

调用示例

如果你的根数据是最外层的reaction数组,直接传入即可:

// 统计总数
const total = countTotalReactions(reaction)
// 统计最大深度
const maxDepth = getMaxDepth(reaction)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:06:00