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

JavaScript ES6:将数组重复元素统计为对象数组的技术需求

解决方案:统计品牌出现次数并转换为目标对象数组

嘿,我来帮你搞定这个产品筛选里的品牌统计问题!思路其实很清晰,分两步走就能完美实现你要的效果:先统计每个生产商的出现次数,再把统计结果转换成指定的对象数组格式。

步骤1:高效统计品牌出现次数

其实你完全不需要先手动去重数组哦——去重反而会丢失次数信息,直接用原始的未去重数组通过reduce方法就能精准统计:

// 假设你的原始品牌数组是这样的
const originalBrands = ["Apple", "Apple", "Apple", "Samsung", "Samsung", "Huawei"];

// 用reduce累加统计每个品牌的出现次数
const brandCountMap = originalBrands.reduce((counts, brand) => {
  // 若品牌已在统计对象中则计数+1,否则初始化为1
  counts[brand] = (counts[brand] || 0) + 1;
  return counts;
}, {});

执行这一步后,brandCountMap会得到一个清晰的统计对象:

{ Apple: 3, Samsung: 2, Huawei: 1 }

步骤2:转换为目标格式的对象数组

接下来用Object.entries()把统计对象拆解成键值对数组,再通过map方法把每一组键值对转换成独立的对象:

const resultArray = Object.entries(brandCountMap).map(([brandName, count]) => {
  return { [brandName]: count };
});

最终resultArray就是你想要的格式:

[ { Apple: 3 }, { Samsung: 2 }, { Huawei: 1 } ]

完整整合代码

把两步合并起来,一行代码也能搞定(当然拆分看更清晰):

const originalBrands = ["Apple", "Apple", "Apple", "Samsung", "Samsung", "Huawei"];

const resultArray = Object.entries(
  originalBrands.reduce((counts, brand) => {
    counts[brand] = (counts[brand] || 0) + 1;
    return counts;
  }, {})
).map(([brand, count]) => ({ [brand]: count }));

console.log(resultArray);

如果之前你已经误去重了数组,那得换回原始数组来统计哦——毕竟去重后每个品牌只会出现一次,统计出来的次数全是1,就失去筛选功能的意义啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:08:11