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

如何依据类型数组统计对象列表中各类型的累计数量?

问题描述

我有一个存储唯一类型的数组(注:原代码存在语法错误,已修正为两种常见正确格式):

// 格式1:字符串数组(推荐)
const types = ["orange", "red", "green"];

// 格式2:对象数组(若原需求是对象结构)
const types = [{type: "orange"}, {type: "red"}, {type: "green"}];

同时有一个包含大量类型对象的列表:

const list = [
  {type: "orange", /* 其他属性 */},
  {type: "orange", /* 其他属性 */},
  {type: "red", /* 其他属性 */},
  // ...更多对象
];

需要基于types数组中的类型,统计list中各类型的出现次数,最终得到如下结构的结果(即使某个类型在list中未出现,也要保留并显示数量为0):

const result = [
  {type: "orange", amount: 2},
  {type: "red", amount: 1},
  {type: "green", amount: 0}
];

我之前尝试的代码没有结合types数组,且存在语法错误,代码如下:

const result = [];
const grouped = list.reduce((groupedTypes, typeObject)) => { // 多余的闭合括号
  const type = typeObject.type;
  if (groupedTypes[type] == null) groupedTypes[type] = [];
  groupedTypes[type].push(typeObject);
  return groupedTypes;
}, {});

for (var item in grouped) {
  result.push({type: item.type, amount: item.length}); // item是字符串键名,无type/length属性
}
解决方案

可以分两步实现:先统计list中各类型的数量,再基于types数组生成符合要求的结果数组。

针对字符串格式的types数组

const types = ["orange", "red", "green"];
const list = [
  {type: "orange"},
  {type: "orange"},
  {type: "red"}
];

// 第一步:用reduce统计各类型出现次数,生成类型-数量映射
const countMap = list.reduce((map, item) => {
  const type = item.type;
  map[type] = (map[type] || 0) + 1;
  return map;
}, {});

// 第二步:遍历types数组,生成最终结果
const result = types.map(type => ({
  type,
  amount: countMap[type] || 0
}));

console.log(result);
// 输出:[{type: "orange", amount: 2}, {type: "red", amount: 1}, {type: "green", amount: 0}]

针对对象格式的types数组

如果你的types确实是对象数组,只需修改第二步的遍历逻辑:

const types = [{type: "orange"}, {type: "red"}, {type: "green"}];

// 第一步的countMap代码不变
const countMap = list.reduce((map, item) => {
  const type = item.type;
  map[type] = (map[type] || 0) + 1;
  return map;
}, {});

// 第二步:遍历对象数组,提取type字段
const result = types.map(obj => ({
  type: obj.type,
  amount: countMap[obj.type] || 0
}));

原代码的错误说明

  1. reduce的参数列表多了一个闭合括号,正确写法是list.reduce((groupedTypes, typeObject) => { ... }, {})
  2. for...in循环中,item是对象的字符串键名,不是数组元素,因此item.type和item.length都是无效的,正确写法应为{type: item, amount: grouped[item].length}
  3. 未结合types数组,导致结果中不会包含list里没有的类型(比如green)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:11:15