函数使用.reduce()返回数组和未定义的值



我编写了这个函数,它应该接受一个图书对象数组,格式如下:

{
id: "5f447132c30e8abe6c988a8b",
title: "veniam voluptate magna ipsum officia",
genre: "Historical Fiction",
authorId: 37,
borrows: [
{
id: "5f446f2ea6b68cf6f85f6e28",
returned: true,
},
{
id: "5f446f2ead0070f44676f2f6",
returned: true,
},
],
}

并返回如下所示的数组:

[
{ name: 'Science', count: 3 },
{ name: 'Classics', count: 2 },
{ name: 'Historical Fiction', count: 1 },
{ name: 'Travel', count: 1 },
{ name: 'Young Adult', count: 1 }
]

所以我写了这个:

function findMostCommonGenres(books) {
const mostCommonGenres = books.reduce((genres, book) => {
const genreObj = genres.find(currGenre => currGenre.name === book.genre);
!genreObj ? genres.push({
name: book.genre,
count: 1,
}) : genreObj.count++;
return genres;
}, []);
mostCommonGenres.sort((genA, genB) => genB.count - genA.count);
mostCommonGenres.splice(5);
console.log(mostCommonGenres);
}

但是由于某些原因,它返回数组和一个未定义的值,像这样:

[
{ name: 'Science', count: 3 },
{ name: 'Classics', count: 2 },
{ name: 'Historical Fiction', count: 1 },
{ name: 'Travel', count: 1 },
{ name: 'Young Adult', count: 1 }
]
undefined

它返回的数组正是我所需要的,但我不确定未定义的来源或如何摆脱它…任何帮助都将不胜感激,谢谢!!

您没有在函数findMostCommonGenres中返回值

如果没有返回值,那么函数默认返回undefined,并取决于在哪里(Chrome devtools为例)你运行这段代码,你会看到返回值打印(在这种情况下是undefined)

这是我写它的方式,以不看到undefined

function findMostCommonGenres(books) {
const mostCommonGenres = books.reduce((genres, book) => {
const genreObj = genres.find(currGenre => currGenre.name === book.genre);
!genreObj ? genres.push({
name: book.genre,
count: 1,
}) : genreObj.count++;
return genres;
}, []);
mostCommonGenres.sort((genA, genB) => genB.count - genA.count);
mostCommonGenres.splice(5);
return mostCommonGenres;
}
console.log(findMostCommonGenres({<your books objects here>}))