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

TypeScript中基于id和code的数组迭代过滤问题求助(Angular7)

解决Angular7/TypeScript数组过滤问题

我来帮你搞定这个问题!你的需求很明确:只保留那些在多个不同id下都出现过的code对应的元素,删掉仅在单个id里出现的code项(比如示例里的TWITTER)。咱们分三步走就能轻松解决:

实现思路

  1. 先统计每个code对应的所有不同id(用Set自动去重,避免同一个id重复计数)
  2. 筛选出那些对应id数量≥2的code(也就是有效code)
  3. 用有效code列表过滤原始数组,留下符合要求的元素

TypeScript代码实现

基础版(直接处理数据)

// 你的原始数据
const data = [
  { "id": 381, "code": "GOOGLE", "comment": "ffff" },
  { "id": 381, "code": "FACEBOOK", "comment": "fff" },
  { "id": 378, "code": "TWITTER", "comment": "zeeer" },
  { "id": 378, "code": "GOOGLE", "comment": "rferer" },
  { "id": 378, "code": "FACEBOOK", "comment": "fefehh" }
];

// 第一步:收集每个code对应的不同id集合
const codeToIds = data.reduce((acc, item) => {
  // 如果当前code还没在映射里,初始化一个空Set
  if (!acc[item.code]) {
    acc[item.code] = new Set<number>();
  }
  // 把当前item的id加入对应code的Set(自动去重)
  acc[item.code].add(item.id);
  return acc;
}, {} as Record<string, Set<number>>);

// 第二步:筛选出在多个id中出现的有效code
const validCodes = Object.keys(codeToIds).filter(code => codeToIds[code].size >= 2);

// 第三步:过滤原始数组,只保留有效code的元素
const filteredData = data.filter(item => validCodes.includes(item.code));

console.log(filteredData);
// 输出结果会移除TWITTER那一项,剩下4个符合要求的元素

Angular7组件集成版

如果要在Angular组件里使用,你可以把逻辑封装成方法,在组件初始化时执行:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  // 原始数据
  data = [
    { "id": 381, "code": "GOOGLE", "comment": "ffff" },
    { "id": 381, "code": "FACEBOOK", "comment": "fff" },
    { "id": 378, "code": "TWITTER", "comment": "zeeer" },
    { "id": 378, "code": "GOOGLE", "comment": "rferer" },
    { "id": 378, "code": "FACEBOOK", "comment": "fefehh" }
  ];
  // 过滤后的结果
  filteredData: typeof this.data = [];

  ngOnInit(): void {
    this.filterValidData();
  }

  private filterValidData(): void {
    const codeToIds = this.data.reduce((acc, item) => {
      if (!acc[item.code]) {
        acc[item.code] = new Set<number>();
      }
      acc[item.code].add(item.id);
      return acc;
    }, {} as Record<string, Set<number>>);

    const validCodes = Object.keys(codeToIds).filter(code => codeToIds[code].size >= 2);

    this.filteredData = this.data.filter(item => validCodes.includes(item.code));
  }
}

关于你之前尝试的代码说明

你之前用forEach和indexOf的思路没抓住核心逻辑——我们需要关注的是code对应的id分布,而不是单个id是否重复。上面的方法通过reduce建立code和id集合的映射,能清晰统计每个code的出现范围,再过滤就很准确了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:20:37