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

TypeScript按指定数组过滤对象数组并去重,代码返回空数组求助

解决数组过滤与去重问题

我来帮你搞定这个问题~你现在的代码返回空数组是因为犯了一个小错误:value是一个数组[1,2],而x.GroupId是单个数字,直接用==把单个值和整个数组比较,当然匹配不上任何项啦!

第一步:修正过滤逻辑

要判断GroupId是否在value数组里,应该用数组的includes()方法,它会检查目标值是否存在于数组中:

// 先实现正确的过滤
let filteredData = this.inventory.filter(x => this.value.includes(x.GroupId));

这一步之后,你会得到包含所有GroupId为1或2的项,也就是:

[
 {id: 1, quantity: 2, GroupId: 1},
 {id: 2, quantity: 0, GroupId: 2},
 {id: 1, quantity: 2, GroupId: 1}
]

第二步:实现去重

接下来要去掉重复的项,这里我们可以根据id(或者结合GroupId,看你的业务需求)来判断唯一性,用reduce()方法来实现:

// 过滤 + 去重的完整代码
let uniqueFilteredData = this.inventory
  .filter(x => this.value.includes(x.GroupId))
  .reduce((acc, current) => {
    // 检查当前项的id是否已经在累加器中存在
    const exists = acc.find(item => item.id === current.id);
    if (!exists) {
      acc.push(current);
    }
    return acc;
  }, [] as typeof this.inventory);

如果你的唯一标识需要同时考虑id和GroupId,可以把判断条件改成:

const exists = acc.find(item => item.id === current.id && item.GroupId === current.GroupId);

这样最终得到的结果就是去重后的过滤数组:

[
 {id: 1, quantity: 2, GroupId: 1},
 {id: 2, quantity: 0, GroupId: 2}
]

另外,如果你想用更简洁的方式去重,也可以结合Set来实现:

let uniqueFilteredData = Array.from(
  new Set(
    this.inventory
      .filter(x => this.value.includes(x.GroupId))
      .map(item => JSON.stringify(item))
  )
).map(item => JSON.parse(item));

这种方式是把每个对象转成字符串存入Set(自动去重),再转成对象数组,适合对象结构完全相同的重复项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:03:29