Home > front end >  function using .reduce() returning array and undefined value
function using .reduce() returning array and undefined value

Time:07-03

I wrote out this function that is supposed to take in an array of book objects that are formatted like this:

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

and return an array that looks like this:

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

so i went and made this:

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

but for some reason it is returning the array AND an undefined value like this:

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

the array it returns is exactly what i need but im not sure where the undefined is coming from or how to get rid of it... any help would be appreciated thanks !!

CodePudding user response:

You are not returning a value in your function findMostCommonGenres

If there is no return value then the function by default returns undefined and depending on where (Chrome devtools as an example) you run this piece of code you will see the return value printed (in this case undefined)

This is how I would write it to not see the 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>}))
  • Related