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

如何使用JavaScript的reduce生成数组中国家占比的指定JSON格式结果?

使用reduce生成国家出现占比的指定格式数组

需求说明

输入数组:

const countriesList = ["US","US","US","UK","IT","IT"]

期望输出格式:

const percCountriesList = [
  {"country": "US", "weight": 0.5},
  {"country": "UK", "weight": 0.1666},
  {"country": "IT", "weight": 0.3333}
]

当前代码及问题

现有计算百分比的代码:

const countriesList = ["US","US","US","UK","IT","IT"]
const weightPercCountries = countriesList.reduce((pcts, x) => {
    pcts[x] = (pcts, (pcts[x] ? pcts[x] : 0) + 100 / countriesList.length);
    return pcts;
}, []);
console.log(weightPercCountries)

当前得到类似 [50, 16.666666666666668, 33.33333333...] 的数组,但需要转换成包含country和weight字段的对象数组。

解决方案

可以通过两步实现,或者直接用reduce一步完成,以下是两种可行方案:

方案一:分阶段处理(更直观)

const countriesList = ["US","US","US","UK","IT","IT"];
const total = countriesList.length;

// 1. 先用reduce统计每个国家的出现次数
const countObj = countriesList.reduce((acc, country) => {
  acc[country] = (acc[country] || 0) + 1;
  return acc;
}, {});

// 2. 将统计结果转换成目标格式,同时计算占比并保留四位小数
const percCountriesList = Object.entries(countObj).map(([country, count]) => ({
  country,
  weight: Number((count / total).toFixed(4))
}));

console.log(percCountriesList);

方案二:单reduce完成

const countriesList = ["US","US","US","UK","IT","IT"];
const total = countriesList.length;

const percCountriesList = Object.values(countriesList.reduce((acc, country) => {
  // 如果当前国家还未存入对象,初始化对应的结构
  if (!acc[country]) {
    acc[country] = { country, weight: 0 };
  }
  // 累加占比并保留四位小数
  acc[country].weight += 1 / total;
  acc[country].weight = Number(acc[country].weight.toFixed(4));
  return acc;
}, {}));

console.log(percCountriesList);

代码说明

  • 两种方案都先基于总长度计算占比,避免重复计算提升效率
  • 用对象存储中间统计结果比数组更合理,避免索引混乱
  • toFixed(4)用于控制小数位数,和期望输出格式匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:40:40