如何统计嵌套tasks数组并按libelle分组,处理无tasks的Profile?
很乐意为你解决这个按libelle分组统计tasks的问题!我会用JavaScript给出具体实现方案,完全贴合你的需求:
核心实现思路
- 先判断当前Profile是否包含
tasks数组,若没有则直接返回计数为0的结果 - 若存在
tasks数组,用对象作为容器,遍历数组按libelle键累加计数 - 最后把统计结果转换成你需要的
"数量X 类型"格式字符串
完整代码示例
首先假设我们有这样的Profile数组:
const profiles = [ { id: 1, tasks: [ { libelle: "CC-Tech" }, { libelle: "CC-Tech" }, { libelle: "EC1" }, { libelle: "EC1" }, { libelle: "EC1" }, { libelle: "EC1" } ] }, { id: 2, // 无tasks数组的Profile }, { id: 3, tasks: [ { libelle: "CC-Tech" }, { libelle: "EC2" } ] } ];
然后编写统计函数:
function getTaskStats(profile) { // 处理无tasks数组或tasks为空的情况 if (!profile.tasks || profile.tasks.length === 0) { return ["0X 任务"]; } // 初始化统计容器 const taskCountMap = {}; // 遍历tasks按libelle分组计数 profile.tasks.forEach(task => { const taskType = task.libelle; // 若当前类型未统计过则初始化为0,再加1 taskCountMap[taskType] = (taskCountMap[taskType] || 0) + 1; }); // 转换为要求的字符串格式 return Object.entries(taskCountMap).map(([type, count]) => `${count}X ${type}`); } // 批量处理所有Profile并输出结果 profiles.forEach(profile => { const stats = getTaskStats(profile); console.log(`Profile ${profile.id}的统计结果:${stats.join("、")}`); });
输出结果
运行后控制台会打印:
Profile 1的统计结果:2X CC-Tech、4X EC1 Profile 2的统计结果:0X 任务 Profile 3的统计结果:1X CC-Tech、1X EC2
扩展需求:显示所有可能的任务类型(含0计数)
如果你需要即使某个Profile没有某类任务,也显示该类型的0计数,可以先收集所有出现过的libelle类型,再统一初始化统计:
// 先收集所有Profile中出现的任务类型 const allTaskTypes = new Set(); profiles.forEach(profile => { if (profile.tasks) { profile.tasks.forEach(task => allTaskTypes.add(task.libelle)); } }); function getFullTaskStats(profile) { // 初始化所有类型的计数为0 const taskCountMap = {}; allTaskTypes.forEach(type => taskCountMap[type] = 0); // 有tasks则累加计数 if (profile.tasks) { profile.tasks.forEach(task => { taskCountMap[task.libelle] += 1; }); } return Object.entries(taskCountMap).map(([type, count]) => `${count}X ${type}`); }
调用这个函数后,Profile 2的结果会变成:0X CC-Tech、0X EC1、0X EC2,适合需要统一统计维度的场景。
内容的提问来源于stack exchange,提问作者DuliNini
相关产品推荐
相关产品推荐

