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

如何使用JS reduce/map/filter统计数组对象属性计数并支持指定查询

JavaScript 犬种计数函数实现

实现逻辑拆解

  • 核心使用reduce方法做遍历汇总,该方法适合将数组遍历结果聚合为单个输出值(本需求中为统计对象)
  • 由于单只狗的breed字段为数组(可能对应多个犬种),需要先展开所有犬种条目再做计数
  • 扩展查询功能只需在拿到全量统计结果后,判断是否传入指定犬种参数,返回对应计数即可

完整代码

const dogs = [
    {
        name:"Cherry",
        breed:["Shiba", "Poodle"]
    },
    {
        name:"Bolt",
        breed:["Shiba"]
    },
    {
        name:"Pumpkin",
        breed:["Chihuahua", "Poodle"]
    },
    {
        name:"Happy",
        breed:["Poodle"]
    },
    {
        name:"Tofu",
        breed:["German Shepherd"]
    }
];

/**
 * 统计犬种出现次数
 * @param {string} [targetBreed] - 可选参数,传入后仅返回对应犬种的计数
 * @returns {object|number} 无参数时返回全量犬种统计对象,传参时返回对应犬种的计数
 */
function countDogBreeds(targetBreed) {
    // reduce初始值为空对象,用于存储犬种-计数的映射关系
    const breedCountMap = dogs.reduce((res, dog) => {
        // 遍历当前狗关联的所有犬种,逐个累加计数
        dog.breed.forEach(breed => {
            res[breed] = (res[breed] || 0) + 1;
        })
        return res;
    }, {});

    // 传入指定犬种时返回对应计数,不存在的犬种默认返回0
    if (targetBreed) {
        return breedCountMap[targetBreed] || 0;
    }
    // 无参数返回全量统计结果
    return breedCountMap;
}

使用示例

  • 获取全量犬种统计结果:
console.log(countDogBreeds());
// 输出: { Shiba: 2, Poodle: 3, Chihuahua: 1, 'German Shepherd': 1 }
  • 查询指定犬种的计数:
console.log(countDogBreeds('Poodle')); // 输出: 3
console.log(countDogBreeds('German Shepherd')); // 输出: 1
console.log(countDogBreeds('Corgi')); // 未收录的犬种输出: 0

分步理解写法(适合新手练习)

如果觉得直接在reduce里嵌套遍历不好理解,可以拆成两步实现,更贴合数组方法的练习场景:

  1. 先用flatMap把所有狗的breed数组拍平成一个一维的全量犬种数组
  2. 再用reduce遍历这个一维数组做计数
// 第一步:提取所有犬种,得到扁平数组 ['Shiba','Poodle','Shiba','Chihuahua','Poodle','Poodle','German Shepherd']
const allBreedList = dogs.flatMap(dog => dog.breed);
// 第二步:遍历计数
const breedCountMap = allBreedList.reduce((res, breed) => {
    res[breed] = (res[breed] || 0) + 1;
    return res;
}, {});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:30:51