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

如何基于属性值移除响应中的重复数组?已尝试filter方法

解决基于attribute_value移除重复数组的问题

嘿,这个去重需求其实很容易搞定!你之前尝试用filter的方向完全正确,只是需要搭配一个辅助工具来记录已经处理过的attribute_value就行。下面给你两种实用的实现思路:

方法一:保留第一个出现的重复项

用Set来存储已经见过的attribute_value,遍历数组时只保留那些首次出现的项:

// 假设你的原始响应数组是这样的
const responseArray = [
  { attribute_value: 1, name: "选项A" },
  { attribute_value: 1, name: "重复选项A" },
  { attribute_value: 1, name: "又一个重复A" },
  { attribute_value: 2, name: "选项B" },
  { attribute_value: 2, name: "重复选项B" },
  { attribute_value: 3, name: "唯一选项C" }
];

// 初始化Set来记录已出现的attribute_value
const seenValues = new Set();

// 过滤出唯一数组项
const uniqueResponse = responseArray.filter(item => {
  // 如果当前值没见过,就加入Set并保留该项
  if (!seenValues.has(item.attribute_value)) {
    seenValues.add(item.attribute_value);
    return true;
  }
  // 已经见过的话就过滤掉
  return false;
});

console.log(uniqueResponse);
// 输出会保留每个attribute_value的第一个出现项:
// [{ attribute_value:1, name:"选项A" }, { attribute_value:2, name:"选项B" }, { attribute_value:3, name:"唯一选项C" }]

方法二:保留最后一个出现的重复项

如果你想保留每个attribute_value最后出现的数组项,可以用reduce把数组转成对象(键为attribute_value,值为对应数组项),最后再转回数组:

const uniqueResponseLast = Object.values(
  responseArray.reduce((acc, item) => {
    // 后面出现的项会覆盖前面的同value项
    acc[item.attribute_value] = item;
    return acc;
  }, {})
);

console.log(uniqueResponseLast);
// 输出会保留每个attribute_value的最后出现项:
// [{ attribute_value:1, name:"又一个重复A" }, { attribute_value:2, name:"重复选项B" }, { attribute_value:3, name:"唯一选项C" }]

这两种方法的时间复杂度都是O(n),只需要遍历一次数组,效率很高。你可以根据需求选择其中一种就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:31:47