如何创建一个函数来返回每个品种的编号?

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
}

编辑:

我开始理解一些概念和功能,但将多个不同的概念结合起来对我来说仍然是一个挑战.

推荐答案

这里不需要reducefiltermap.

  1. 创建一个对象以按品种对分数进行分组.
  2. Iterate over the dogs array,然后迭代每只狗的品种array.如果品种doesn't already exist on the object创建它并将值设置为零.
  3. 在"品种"值中添加一个.

对于您关于传入一个单独的breed参数以获取该品种的总数的 comments ,只需稍微修改一下函数即可.

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

其他文件

Javascript相关问答推荐

Math.random超出了最大调用堆栈

Vue v模型检测父参考更改

即使设置了父级的最大高度,固定位置的分区内容也不会滚动?

鼠标移动时更新画布

积分计算和 colored颜色 判断错误

为什么JavaScript双边字符串文字插值不是二次的?

微软Edge Select 间隙鼠标退出问题

被CSS优先级所迷惑

togglePopover()不打开但不关闭原生HTML popover'

React 17与React 18中的不同setState行为

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

变量的值在Reaction组件中的Try-Catch语句之外丢失

使用ThreeJ渲染的形状具有抖动/模糊的边缘

更新动态数据中对象或数组中的所有值字符串

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

变量在导入到Vite中的另一个js文件时成为常量.

React:防止useContext重新渲染整个应用程序或在组件之间共享数据而不重新渲染所有组件

MongoDB中的嵌套搜索

如何在FiRestore中的事务中使用getCountFromServer

我的NavLink活动类在REACT-ROUTER-V6中出现问题