如何递归统计嵌套数组中分组的总设备数量?
嵌套分组设备总数统计问题修复
需求背景
现有一个支持n层嵌套的分组数组结构,每个分组包含自身设备列表和子分组,需要用TypeScript递归函数统计每个分组下自身+所有子分组的设备总数。
原数组结构
const array = [ { "groupId": "group1", "devices": ["5","6"], "children": [ { "groupId": "group11", "devices": ["1","2","3","4"], "children": [ { "groupId": "group111", "devices": ["7","8","9","0"], "children": [] }, { "groupId": "group112", "devices": ["7","8","9","0"], "children": [] } ] }, { "groupId": "group12", "devices": ["1","2","3","4"], "children": [ { "groupId": "group121", "devices": ["7","8","9","0"], "children": [] } ] } ] } ];
预期结果
group1 : 22 group11 : 12 group111 : 4 group112 : 4 group12 : 8 group121 : 4
注:原预期示例遗漏了group112和group12的统计,这里补充完整符合逻辑的结果
原代码问题分析
原递归方法的核心问题:
- 值传递导致递归结果无法回溯:
devcount是基本类型,递归调用时传入的是值副本,子分组的计算结果无法传递回父分组 - 计数逻辑错误:每个分组的总设备数应该是自身设备数 + 所有子分组的总设备数,而非依赖外部传入的累计值
devcount重置时机错误:在循环内重置会打断父分组的累计逻辑
原错误代码:
this.getdevicesCount(this.array, 0); /** * Recursive method to find Number of devices in a group */ getdevicesCount(array: any[], devcount: number) { array.forEach((group) => { devcount = devcount + group.devices.length; if(group.children.length) { this.getdevicesCount(group.children, devcount); } group.count = devcount; devcount = 0; }); }
修正后的代码
修改思路:让递归函数返回当前分组及其所有子分组的总设备数,每个分组通过自身设备数加上子分组返回值的总和,得到自己的总设备数。同时定义类型提升代码健壮性。
// 先定义分组的类型 interface Group { groupId: string; devices: string[]; children: Group[]; count?: number; // 新增统计结果字段 } const array: Group[] = [ // 原数组内容不变 ]; /** * 递归统计分组设备总数,并为每个分组添加count属性 * @param groups 分组数组 * @returns 当前层级所有分组的总设备数(供父分组计算使用) */ const getDevicesCount = (groups: Group[]): number => { let total = 0; groups.forEach(group => { // 自身设备数 let groupTotal = group.devices.length; // 递归计算子分组总设备数,并累加 if (group.children.length > 0) { groupTotal += getDevicesCount(group.children); } // 为当前分组设置统计结果 group.count = groupTotal; // 累加到当前层级的总设备数(返回给父分组) total += groupTotal; }); return total; }; // 调用函数 getDevicesCount(array); // 打印结果(可按需求调整输出格式) const printResults = (groups: Group[]) => { groups.forEach(group => { console.log(`${group.groupId} : ${group.count}`); if (group.children.length > 0) { printResults(group.children); } }); }; printResults(array);
关键修正点
- 使用返回值传递递归结果:子分组的统计结果通过返回值传递给父分组,解决值传递的问题
- 正确的计数逻辑:每个分组的总设备数 = 自身设备数 + 所有子分组的总设备数
- 类型定义:新增
Group接口,避免any类型,提升代码可维护性 - 独立的分组统计:每个分组的统计不依赖外部传入的累计值,逻辑更清晰
内容的提问来源于stack exchange,提问作者jitenderd
相关产品推荐
相关产品推荐

