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

JavaScript如何基于对象数组按分类统计最低价格和数量生成新数组

按分类聚合对象数组计算最低价格和分类条目数

原始输入数据

const arr = [
    {
      categoryId: "I01",
      categoryName: "Category_one",
      price: 100
    },
    {
      categoryId: "I02",
      categoryName: "Category_two",
      price: 200
    },
    {
      categoryId: "I03",
      categoryName: "Category_three",
      price: 300
    },
    {
      categoryId: "I02",
      categoryName: "Category_two",
      price: 210
    },
    {
      categoryId: "I03",
      categoryName: "Category_three",
      price: 310
    }
 ]

预期输出结构

arr2 = [
    {
      id: 0,
      categoryId: "I01",
      categoryName: "Category_one",
      minimum_price: 100,
      count: 1
    },
    {
      id: 1,
      categoryId: "I02",
      categoryName: "Category_two",
      minimum_price: 200,
      count: 2
    },
    {
      id: 2,
      categoryId: "I03",
      categoryName: "Category_three",
      minimum_price: 300,
      count: 2
    },
]

已有实现

目前已完成分类去重、添加序号ID的逻辑:

const resArr = [];
arr.forEach((item) => {
    let i = resArr.findIndex(x => x.categoryId == item.categoryId);
    if (i <= -1) {
        resArr.push({ categoryId: item.categoryId, categoryName: item.categoryName });
    }
});
resArr.forEach((o, i) => o.id = i);

得到的中间结果:

res = [
        {
          id: 0,
          categoryId: "I01",
          categoryName: "Category_one"
        },
        {
          id: 1,
          categoryId: "I02",
          categoryName: "Category_two"
        },
        {
          id: 2,
          categoryId: "I03",
          categoryName: "Category_three"
        },
    ]

实现方案

你可以在第一次遍历原数组的阶段同步统计分类条目数和最低价格,无需额外多轮遍历,修改后代码如下:

const resArr = [];
arr.forEach((item) => {
    const existIndex = resArr.findIndex(x => x.categoryId === item.categoryId);
    if (existIndex === -1) {
        // 分类首次出现时初始化字段
        resArr.push({
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            minimum_price: item.price,
            count: 1
        });
    } else {
        // 分类已存在时更新统计字段
        resArr[existIndex].count += 1;
        if (item.price < resArr[existIndex].minimum_price) {
            resArr[existIndex].minimum_price = item.price;
        }
    }
});
// 为分类结果添加序号ID
resArr.forEach((o, i) => o.id = i);

最终resArr就是符合要求的输出结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:36:04