How to use reduce, map, or filter to create a function to display and count each values of array objects?

How can I create a function that will return the number of each 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"]
    }
];

I want to print each breeds and its count like below.

{
German Shepherd: 1,
Shiba: 2,
Poodle: 3,
Chihuahua:1
}

>Solution :

You can use reduce and repeat that on the nested arrays:

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"]}];

const result = dogs.reduce((acc, {breed}) => 
    breed.reduce((acc, name) => {
        acc[name] = (acc[name] ?? 0) + 1;
        return acc;
    }, acc)
, {});

console.log(result);

Alternatively, you could first flatten the data into an array of strings, and then reduce that:

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"]}];

const result = dogs.flatMap(({breed}) => breed).reduce((acc, name) => {
    acc[name] = (acc[name] ?? 0) + 1;
    return acc;
}, {});

console.log(result);

Leave a Reply