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

如何用Lodash遍历对象数组统计MARKET出现次数并格式化排序

实现方案

1. 统计MARKET出现次数

使用Array.reduce遍历原始数据源,仅需一次遍历即可完成计数,同时使用Object.create(null)创建映射表避免原型链污染,匹配你之前消除对象prototype的需求:

// sourceData为你的原始数据数组
const marketCountMap = sourceData.reduce((map, item) => {
  const currentMarket = item.MARKET
  map[currentMarket] = (map[currentMarket] || 0) + 1
  return map
}, Object.create(null))

2. 生成目标结构数组

遍历计数映射表生成符合要求的对象结构:

const result = Object.entries(marketCountMap).map(([market, count]) => ({
  name: market,
  displayName: market,
  count: count
}))

如果你已经提前得到了去重后的newMarketArray,可以直接复用它生成结果:

const result = newMarketArray.map(market => ({
  name: market,
  displayName: market,
  count: marketCountMap[market]
}))

3. 排序

可根据实际需求选择排序规则,以下提供两种常用方案:

  • 按MARKET名称字母升序排序:
result.sort((a, b) => a.name.localeCompare(b.name))
  • 按count计数从高到低降序排序:
result.sort((a, b) => b.count - a.count)

以你提供的示例源数据为例,最终输出结果如下:

[
  { name: 'IL', displayName: 'IL', count: 2 },
  { name: 'WA', displayName: 'WA', count: 2 },
  { name: 'OR', displayName: 'OR', count: 1 }
]

内容的提问来源于stack exchange,提问作者Peter The Angular Dude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:06:07