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

如何用原生JS或Lodash实现带分类限制的拉美凶杀率数据聚合

解决方案:按年份聚合凶杀率数据,保留Top N国家并合并其余为Others

核心逻辑

针对每个年份单独处理:

  • 将该年份的所有国家数据按凶杀率降序排序
  • 保留前 maxCategories - 1 个高凶杀率国家
  • 剩余国家的凶杀率累加,生成「others」条目
  • 合并所有年份的处理结果得到最终聚合数据

完整实现代码

const data = [ 
  { year: '2020', country: 'Brazil', homicides: 0.60 },
  { year: '2020', country: 'Argentina', homicides: 0.10 }, 
  { year: '2020', country: 'Venezuela', homicides: 0.09 }, 
  { year: '2020', country: 'Uruguay', homicides: 0.08 }, 
  { year: '2020', country: 'Paraguay', homicides: 0.04 }, 
  { year: '2020', country: 'Bolivia', homicides: 0.03 }, 
  { year: '2020', country: 'Peru', homicides: 0.02 }, 
  { year: '2020', country: 'Chile', homicides: 0.02 }, 
  { year: '2020', country: 'Equador', homicides: 0.02 }, 
  { year: '2021', country: 'Brazil', homicides: 0.70 }, 
  { year: '2021', country: 'Venezuela', homicides: 0.10 }, 
  { year: '2021', country: 'Ecuador', homicides: 0.08 }, 
  { year: '2021', country: 'Argentina', homicides: 0.06 }, 
  { year: '2021', country: 'Paraguay', homicides: 0.02 }, 
  { year: '2021', country: 'Uruguay', homicides: 0.02 }, 
  { year: '2021', country: 'Chile', homicides: 0.01 },   
  { year: '2021', country: 'Peru', homicides: 0.01 }
];

// 可配置的最大分类数
const maxCategories = 6;

// 1. 按年份分组数据
const groupedByYear = {};
data.forEach(item => {
  if (!groupedByYear[item.year]) {
    groupedByYear[item.year] = [];
  }
  groupedByYear[item.year].push(item);
});

// 2. 处理每个年份的数据
const aggregatedData = [];
Object.keys(groupedByYear).forEach(year => {
  const yearData = groupedByYear[year];
  
  // 按凶杀率降序排序
  const sorted = yearData.sort((a, b) => b.homicides - a.homicides);
  
  // 保留前maxCategories-1个国家
  const topCountries = sorted.slice(0, maxCategories - 1);
  
  // 计算剩余国家的凶杀率总和
  const othersSum = sorted.slice(maxCategories - 1)
    .reduce((total, item) => total + item.homicides, 0);
  
  // 添加top国家到结果
  aggregatedData.push(...topCountries);
  
  // 仅当有剩余国家时添加others条目
  if (othersSum > 0) {
    aggregatedData.push({
      year,
      country: 'others',
      homicides: othersSum
    });
  }
});

console.log(aggregatedData);

代码说明

  • 分组处理:通过groupedByYear对象将原始数据按年份拆分,确保每个年份的数据独立处理
  • 排序逻辑:使用sort((a,b) => b.homicides - a.homicides)实现凶杀率从高到低排序
  • 动态筛选:通过maxCategories - 1计算需要保留的国家数量,确保最终每个年份的分类数不超过设定的最大值
  • Others计算:使用slice截取剩余数据,再通过reduce累加凶杀率,仅当总和大于0时才添加「others」条目(避免无剩余国家时出现空条目)

运行代码后,输出结果将完全匹配你提供的aggregatedData示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:53:14