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);