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

如何按art字段分组哈希数组 聚合id列表并统计各art条目总数

按art字段分组数组并统计条目数实现方案

实现逻辑

核心是利用JS对象键的唯一性做哈希映射,遍历原数组时将相同art值的条目id归集到对应分组,最后将映射结果转为目标数组结构即可,分组对应的总条目数可以直接通过归集的id数组长度获取,也可以单独维护计数字段。

基础实现代码(输出和期望结构完全一致)

// 原始输入数组
const sourceArr = [
  { id: 1, art: "art_123" },
  { id: 2, art: "art_234" },
  { id: 3, art: "art_123" }
];

// 分组处理
const groupRes = Object.values(sourceArr.reduce((groupMap, currentItem) => {
  // 初始化当前art对应的分组结构
  if (!groupMap[currentItem.art]) {
    groupMap[currentItem.art] = {
      art: currentItem.art,
      ids: []
    };
  }
  // 归集当前条目id到对应分组
  groupMap[currentItem.art].ids.push(currentItem.id);
  return groupMap;
}, {}));

console.log(groupRes);
// 输出:[ { art: 'art_123', ids: [ 1, 3 ] }, { art: 'art_234', ids: [ 2 ] } ]

条目数统计方式

  • 如果需要在结果中直接携带每个分组的总条目数,可以在初始化分组时增加totalCount字段,遍历过程中累加即可:
const groupResWithCount = Object.values(sourceArr.reduce((groupMap, currentItem) => {
  if (!groupMap[currentItem.art]) {
    groupMap[currentItem.art] = {
      art: currentItem.art,
      ids: [],
      totalCount: 0
    };
  }
  groupMap[currentItem.art].ids.push(currentItem.id);
  groupMap[currentItem.art].totalCount += 1;
  return groupMap;
}, {}));
// 输出:[ { art: 'art_123', ids: [ 1, 3 ], totalCount: 2 }, { art: 'art_234', ids: [ 2 ], totalCount: 1 } ]
  • 如果不需要额外字段,直接读取分组结果中ids数组的length属性,就是该art对应的总条目数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:15:37