如何创建一个返回每个品种数量的函数?
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"]
}
];
我想打印每个品种及其数量,如下所示。
{
German Shepherd: 1,
Shiba: 2,
Poodle: 3,
Chihuahua:1
}
编辑:另外,我如何将特定品种作为参数传递并仅打印该品种及其数量?
我开始了解一些概念和功能,但将多个不同的概念结合起来对我来说仍然具有挑战性。
这里没有真正需要reduce
, filter
, 或map
。
为了回答您关于传入单独的品种参数以获得该品种的总数的评论,只需稍微修改函数即可。
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"]}];
// Pass in the dogs array
// and an optional query string
function getBreedCount(dogs, query) {
// Grouping object
const obj = {};
// Iterate over the dogs, and the breeds
// updating the grouping object as we go
for (const dog of dogs) {
for (breed of dog.breed) {
obj[breed] ??= 0;
++obj[breed];
}
}
// If there is a query argument...
if (query) {
// ...and the query string is a key on the object
// Return a string: `<breed>: <value>`...
if (obj[query]) return `${query}: ${obj[query]}`;
// ...otherwise return a message that
// the breed doesn't exist
return `${query} doesn't exist`;
}
// If there is no query argument
// return the complete object
return obj;
}
console.log(getBreedCount(dogs));
console.log(getBreedCount(dogs, 'Poodle'));
console.log(getBreedCount(dogs, 'Shiba'));
console.log(getBreedCount(dogs, 'Bobby Davro'));
附加文件
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句