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

Angular 如何将PartsChildInfo列表过滤去重为PartGroupInfo列表

问题原因

代码存在3个核心问题:

  1. 初始状态下testChildList是空数组,第二层for循环的判断条件j < this.testChildList.length永远不成立,循环体一次都不会执行,没有元素被推入数组,因此结果为空
  2. 去重判断逻辑错误:当前判断条件是「两个字段都不相等才新增」,正确逻辑应为「只要存在任意一个已有条目和当前条目两个字段都相等,就判定为重复,不需要新增;只有所有已有条目都不重复时才新增」
  3. 属性名大小写需要统一:类定义里属性是小写开头的materialName/thickNess,示例数据里写的是大写开头的MaterialName/ThickNess,如果实际运行时属性名不统一会导致取到undefined,去重逻辑失效

修复后的循环实现

testChildList: PartGroupInfo[] = [];
for (let i = 0; i < list.length; i++) {
  const targeti = list[i];
  // 标记当前条目是否已存在
  let isExist = false;
  for (let j = 0; j < this.testChildList.length; j++) {
    const targetj = this.testChildList[j];
    // 两个字段都相等则判定为已存在
    if (targeti.materialName === targetj.materialName && targeti.thickNess === targetj.thickNess) {
      isExist = true;
      break;
    }
  }
  // 不存在才添加到结果数组
  if (!isExist) {
    const item = new PartGroupInfo();
    item.materialName = targeti.materialName;
    item.thickNess = targeti.thickNess;
    this.testChildList.push(item);
  }
}

优化实现(时间复杂度更低)

使用Set存储已出现的字段组合,代码更简洁,执行效率更高:

const uniqueKeySet = new Set<string>();
const testChildList: PartGroupInfo[] = list.reduce((result, current) => {
  const combineKey = `${current.materialName}_${current.thickNess}`;
  if (!uniqueKeySet.has(combineKey)) {
    uniqueKeySet.add(combineKey);
    const groupItem = new PartGroupInfo();
    groupItem.materialName = current.materialName;
    groupItem.thickNess = current.thickNess;
    result.push(groupItem);
  }
  return result;
}, []);

内容的提问来源于stack exchange,提问作者dev.for.live

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:45:03