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

如何基于对象内部variants数组对JS对象数组实现归约去重

产品数组按规则去重实现

原始数据集结构

[
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['3 Pack of Nappies', 'small']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['6 Pack of Nappies', 'small']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['12 Pack of Nappies', 'small']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['3 Pack of Nappies', 'medium']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['6 Pack of Nappies', 'medium']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['12 Pack of Nappies', 'medium']
  },
  {
    id: 'def',
    productType: "Wipes",
    variants: ['3 Pack of Wipes']
  },
  {
    id: 'def',
    productType: "Wipes",
    variants: ['6 Pack of Wipes']
  },
  {
    id: 'def',
    productType: "Wipes",
    variants: ['12 Pack of Wipes']
  },
]

去重规则

  • 同一id的产品,只要variants数组首个"X Pack of XX"格式的元素相同,仅保留任意一条
  • 无需关注variants数组后续的尺寸类参数

原代码问题说明

你提供的代码无法生效有两个核心问题:

  1. 属性引用错误:数据集内存储变体的属性为variants,代码中错误使用了不存在的selectedOptions属性
  2. 逻辑完全颠倒:原代码过滤出累计数组中匹配的元素后再追加当前项,本质是在累加重复数据,完全不符合去重要求

正确实现代码

我们可以通过reduce搭配Set实现高效去重,用id + variants[0]作为唯一判断标识:

const removeDuplicates = (array) => {
  // 存储已出现过的唯一标识,避免重复判断
  const existedKeys = new Set()
  return array.reduce((result, currentItem) => {
    // 生成当前项的唯一判断key
    const uniqueKey = `${currentItem.id}-${currentItem.variants[0]}`
    // 仅当标识未出现过时,才将当前项加入结果
    if (!existedKeys.has(uniqueKey)) {
      existedKeys.add(uniqueKey)
      result.push(currentItem)
    }
    return result
  }, [])
}

如果不想额外引入Set,也可以直接在累计结果数组中判断,适合小数据量场景:

const removeDuplicates = (array) => {
  return array.reduce((result, currentItem) => {
    const isExisted = result.some(item => 
      item.id === currentItem.id && item.variants[0] === currentItem.variants[0]
    )
    if (!isExisted) {
      result.push(currentItem)
    }
    return result
  }, [])
}

输出结果

调用上述函数处理原始数据集,即可得到你预期的输出:

[
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['3 Pack of Nappies', 'small']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['6 Pack of Nappies', 'small']
  },
  {
    id: 'abc',
    productType: "Nappies",
    variants: ['12 Pack of Nappies', 'small']
  },
  {
    id: 'def',
    productType: "Wipes",
    variants: ['3 Pack of Wipes']
  },
  {
    id: 'def',
    productType: "Wipes",
    variants: ['6 Pack of Wipes']
  },
  {
    id: 'def',
    productType: "Wipes",
    variants: ['12 Pack of Wipes']
  },
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:06:00