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

如何在JavaScript中将数组中符合条件的项归为‘Other’分组以优化饼图数据

Fixing Pie Chart Data by Merging Small Categories in JavaScript

Got it, let's tweak your code to match exactly what you need! Your core approach is solid—you just need to adjust the threshold from 10 to 5, plus a small check to avoid adding an empty "Other" category when there are no small items to merge.

Here's the revised, working function:

const getLanguageData = () => {
  // First, filter to keep only language-related entries
  const languageData = metricsPies.filter(item => item.type === 'language');
  
  // Keep entries with count >= 5 (your desired threshold)
  const mainCategories = languageData.filter(item => item.count >= 5);
  
  // Calculate total count for all small categories (count < 5)
  const othersTotal = languageData
    .filter(item => item.count < 5)
    .reduce((sum, item) => sum + item.count, 0);
  
  // Only add "Other" if there's actually data to merge (avoids empty slice)
  if (othersTotal > 0) {
    mainCategories.push({
      label: 'Other',
      count: othersTotal,
      type: 'language'
    });
  }
  
  return mainCategories;
};

Let's walk through what this does:

  • Filter language data: We first narrow down your metricsPies array to only items tagged as "language"—your original code already handled this perfectly.
  • Isolate main categories: We keep any entry with a count of 5 or higher, which in your sample data will only be English (747).
  • Sum small category counts: We use filter to grab all items with counts under 5, then reduce to add up their total count (which equals 19 in your sample).
  • Conditionally add "Other": We only push the "Other" entry if there's actual data to merge—this prevents an unnecessary empty slice in your pie chart if all categories meet the threshold.

When you run this with your sample data, you'll get exactly the output you wanted:

[
  {label: "English", count: 747, type: "language"},
  {label: "Other", count: 19, type: "language"}
]

If you ever need to adjust the threshold later, just change the 5 in the filter conditions to your new value—super easy to maintain!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:28:11