Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading