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

JavaScript如何按对象多属性过滤数组并实现去重?

如何根据对象的多个属性组合对数组去重

你需要对包含车辆信息的数组,按照name和brand的组合进行去重,保留每个唯一组合的第一个实例。你的原代码无法实现需求,问题出在以下几点:

  • 代码中name和brand是未定义的变量,没有具体匹配值
  • 使用了位运算符&,逻辑判断应该用逻辑与运算符&&
  • 整体逻辑是筛选匹配特定name和brand的项,而非对组合进行去重

下面是两种可行的实现方式:

方法一:使用Set结合filter

利用Set的唯一性特性,记录已经出现过的name+brand组合,遍历数组时只保留未出现过的组合项:

const vehicles = [
  { "name": "Ford", "type": "SUV", "brand": "Explorer" },
  { "name": "Ford", "type": "SUV", "brand": "Explorer" },
  { "name": "Ford", "type": "truck", "brand": "F-150" },
  { "name": "Chrysler", "type": "car", "brand": "Sierra" },
  { "name": "GM", "type": "truck", "brand": "Sierra" },
  { "name": "GM", "type": "truck", "brand": "Sierra" },
];

const seenCombinations = new Set();
const filteredVehicles = vehicles.filter(item => {
  // 生成唯一标识组合的键
  const combinationKey = `${item.name}-${item.brand}`;
  if (!seenCombinations.has(combinationKey)) {
    seenCombinations.add(combinationKey);
    return true;
  }
  return false;
});

console.log(filteredVehicles);

方法二:使用reduce构建唯一对象后转数组

通过reduce将数组转换为以name+brand组合为键的对象,利用对象键的唯一性去重,最后提取对象的值得到去重后的数组:

const vehicles = [
  { "name": "Ford", "type": "SUV", "brand": "Explorer" },
  { "name": "Ford", "type": "SUV", "brand": "Explorer" },
  { "name": "Ford", "type": "truck", "brand": "F-150" },
  { "name": "Chrysler", "type": "car", "brand": "Sierra" },
  { "name": "GM", "type": "truck", "brand": "Sierra" },
  { "name": "GM", "type": "truck", "brand": "Sierra" },
];

const filteredVehicles = Object.values(vehicles.reduce((acc, item) => {
  const combinationKey = `${item.name}-${item.brand}`;
  // 仅当键不存在时才添加当前项
  if (!acc[combinationKey]) {
    acc[combinationKey] = item;
  }
  return acc;
}, {}));

console.log(filteredVehicles);

两种方法都能得到你想要的结果,保留每个name+brand组合的第一个实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:17:47