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

如何查找数组中total_sales.cents值重复的对象元素?

找出数组中total_sales.cents值重复的元素

可以通过统计频次+筛选的方式快速定位重复元素,以下是具体实现(以JavaScript为例):

原始数据

const top_products = [
  {
    "name": "Unknown New Perfume",
    "total_quantity": 8,
    "total_sales": {
      "cents": 160000,
      "currency_iso": "MYR"
    }
  },
  {
    "name": "product2",
    "total_quantity": 5,
    "total_sales": {
      "cents": 11500,
      "currency_iso": "MYR"
    }
  },
  {
    "name": "Lolo perfume",
    "total_quantity": 4,
    "total_sales": {
      "cents": 3600,
      "currency_iso": "MYR"
    }
  },
  {
    "name": "product1",
    "total_quantity": 3,
    "total_sales": {
      "cents": 3600,
      "currency_iso": "MYR"
    }
  }
];

实现步骤

方法一:用普通对象统计频次

// 1. 遍历数组,统计每个cents的出现次数
const centsCount = {};
top_products.forEach(item => {
  const cents = item.total_sales.cents;
  centsCount[cents] = (centsCount[cents] || 0) + 1;
});

// 2. 筛选出出现次数大于1的元素
const duplicateItems = top_products.filter(item => centsCount[item.total_sales.cents] > 1);

console.log(duplicateItems);
// 输出结果为两个cents值为3600的元素

方法二:用Map统计频次(适配复杂键类型)

// 1. 用Map统计频次
const centsMap = new Map();
top_products.forEach(item => {
  const cents = item.total_sales.cents;
  centsMap.set(cents, (centsMap.get(cents) || 0) + 1);
});

// 2. 筛选重复元素
const duplicateItems = top_products.filter(item => centsMap.get(item.total_sales.cents) > 1);

说明

两种方法逻辑一致:先遍历一次数组记录每个total_sales.cents的出现次数,再遍历一次数组筛选出次数大于1的元素,时间复杂度为O(n),效率较高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:24