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

React如何从嵌套数组中筛选answersTo下重复的idCategoria值

嵌套结构提取重复idCategoria实现方案

你现有代码仅做了日志打印,没有做值收集和频次统计,按以下逻辑实现即可,不需要提前预设对比值:

  • 扁平化遍历三层嵌套结构,收集全量idCategoria值
  • 统计每个id的出现频次
  • 筛选出出现次数≥2的id,自动去重后就是目标重复项集合

实现代码

// 收集所有层级的idCategoria
const allCateIds: Array<string | number> = [];
previewData.forEach((getPrev: any) => {
  getPrev.answers?.forEach((getAns: any) => {
    getAns.answersTo?.forEach((getAnsTo: any) => {
      if (getAnsTo?.idCategoria != null) {
        allCateIds.push(getAnsTo.idCategoria);
      }
    });
  });
});

// 统计id出现频次
const countMap = new Map<string | number, number>();
allCateIds.forEach(id => {
  countMap.set(id, (countMap.get(id) ?? 0) + 1);
});

// 过滤出重复出现的id
const duplicateCateIds = Array.from(countMap.entries())
  .filter(([_, count]) => count > 1)
  .map(([id]) => id);

// duplicateCateIds即为最终结果,正常情况下长度会匹配你预期的5个
console.log('重复idCategoria结果:', duplicateCateIds);

实现说明:

  1. 纯遍历收集值的场景不要用map,map的作用是映射返回新数组,用forEach遍历性能更优
  2. 代码里加了可选链?.和空值判断,避免接口返回空字段时抛出JS错误
  3. 用Map做频次统计不会出现隐式类型转换问题,不管id是字符串还是数字类型都能准确统计
  4. 最终返回的结果已经去重,不会出现同一个id多次返回的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:45:33