Javascript 教程,在映射和减少以获得正确答案时遇到问题

标签 javascript arrays nested reduce

我正在尝试完成本教程,但我无法弄清楚为什么讲师给出的答案对我不起作用。

有一个用户(对象)数组,每个用户都有 favoriteBooks 作为嵌套对象。

我们将使用map和reduce来创建所有用户最喜欢的书籍的数组。

我在底部的代码是迄今为止我所拥有的,但也是讲师所说的解决方案。他的代码可以创建精确的解决方案(在他的视频中)。

但是,我认为问题是当第二张 map 发挥作用时,仍然需要通过另一层嵌套数组。

有人可以解释一下吗?我一生都无法弄清楚。

谢谢!

const users = [
  {
    name: 'Samir',
    age: 27,
    favoriteBooks:[
      {title: 'The Iliad'},
      {title: 'The Brothers Karamazov'}
    ]
  },
  {
    name: 'Angela',
    age: 33,
    favoriteBooks:[
      {title: 'Tenth of December'},
      {title: 'Cloud Atlas'},
      {title: 'One Hundred Years of Solitude'}
    ]
  },
  {
    name: 'Beatrice',
    age: 42,
    favoriteBooks:[
      {title: 'Candide'}
    ]
  }
];

    // Result: ['The Iliad', 'The Brothers Karamazov', 'Tenth of December', 'Cloud Atlas', 'One Hundred Years of Solitude', 'Candide'];

var books = users
  .map(function(user) {
    return user.favoriteBooks;
  })
  .map(function(book) {
    return book.title;
  })
  .reduce(function(arr, titles) {
    return [ ...arr, ...titles ];
  }, []);

console.log(books);

最佳答案

您需要reduce函数来展平嵌套数组,并需要map函数来返回reducer内每个用户的书名。最后,使用一些扩展运算符,您可以填充 reducer 的累加器(arr)并获取整个列表。

const users = [
  {
    name: 'Samir',
    age: 27,
    favoriteBooks:[
      {title: 'The Iliad'},
      {title: 'The Brothers Karamazov'}
    ]
  },
  {
    name: 'Angela',
    age: 33,
    favoriteBooks:[
      {title: 'Tenth of December'},
      {title: 'Cloud Atlas'},
      {title: 'One Hundred Years of Solitude'}
    ]
  },
  {
    name: 'Beatrice',
    age: 42,
    favoriteBooks:[
      {title: 'Candide'}
    ]
  }
];

    // Result: ['The Iliad', 'The Brothers Karamazov', 'Tenth of December', 'Cloud Atlas', 'One Hundred Years of Solitude', 'Candide'];

const books = users
  .reduce((arr, user) => {
    const favBooks = user.favoriteBooks;
    
    return [...arr, ...favBooks.filter(el => (arr.indexOf(el.title) < 0)).map(el => el.title)];
  }, []);

console.log(books);

关于Javascript 教程,在映射和减少以获得正确答案时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49790202/

相关文章:

python - Numpy 分割数组,其中 NaN 结束

controller - JavaFx 嵌套 Controller (FXML <include>)

python - 将 dict 的嵌套列表展平为 Pandas Dataframe

javascript - 如何从 JSON 字符串调用 javascript 函数?

javascript - 带选择的动态表单输入

javascript - 如果其他打开则关闭切换框

javascript - 如何在提交 POST 请求后通过 GET 请求呈现我的最新数据

Java 和数组操作

arrays - 查找数组中重复子数组的数量

mongodb - 在深度嵌套文档查询中使用 MongoDB 的位置运算符 $