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

如何高效按category和group多属性分组对象?无第三方库依赖

按多属性高效分组:先按category再按group

要实现先按category、再按group的层级分组,同时生成包含totalSources和sources的指定格式,用原生数组reduce方法就能高效完成,不需要第三方工具。

示例数据

const items = [
    {
        "name": "Halloumi",
        "group": "Cheese",
        "category": "Dairy"
    },
    {
        "name": "Mozzarella",
        "group": "Cheese",
        "category": "Dairy"
    }
];

正确实现代码

const groupedResult = items.reduce((acc, item) => {
    const { category, group, name } = item;
    
    // 查找或创建当前分类对象
    let categoryEntry = acc.find(entry => entry.category === category);
    if (!categoryEntry) {
        categoryEntry = { category, groups: [] };
        acc.push(categoryEntry);
    }
    
    // 查找或创建当前分类下的分组对象
    let groupEntry = categoryEntry.groups.find(g => g.group === group);
    if (!groupEntry) {
        groupEntry = { group, totalSources: 0, sources: [] };
        categoryEntry.groups.push(groupEntry);
    }
    
    // 添加元素并更新统计值
    groupEntry.sources.push({ name });
    groupEntry.totalSources = groupEntry.sources.length;
    
    return acc;
}, []);

console.log(groupedResult);

输出结果

[
    {
        "category": "Dairy",
        "groups": [
            {
                "group": "Cheese",
                "totalSources": 2,
                "sources": [
                    { "name": "Halloumi" },
                    { "name": "Mozzarella" }
                ]
            }
        ]
    }
]

原实现的问题说明

  • 第一个实现仅完成了category层级的分组,没有处理group的二次分组,结构不符合预期;
  • 第二个实现存在未定义变量(acc、id、theme),且未对group做存在性判断,每个条目都会新增一个分组对象,无法实现合并分组的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:11:09