In my movies array with reduce function I'm trying to make genre of the book an id and if the book has more than one genre the first one should be used as id. The code I wrote is not working the way it should. What is wrong with my code and how can I make it work the correct way
const movies = [
{
title: 'Harry Potter',
genre: 'fantasy'
},
{
title:'Bridgerton',
genre:'romance'
},
{
title: 'Chesnut Man',
genre: 'crime'
},
{
title: 'Little Women',
genre: 'romance'
},
{
title:'The Mask',
genre: 'comedy'
},
{
title:'Holidate',
genre: ['comedy', 'romance']
}]
`
/*
//correct output
{
fantasy: { title: 'Harry Potter', genre: 'fantasy' },
romance: {{ title: 'Little Women', genre: 'romance' },{ title: 'Holidate', genre: 'romance' },}}
crime: { title: 'Chesnut Man', genre: 'crime' },
comedy: {{ title: 'The Mask', genre: 'comedy'},{ title: 'Holidate', genre: 'comedy' } }
}
*/
// my code
const genreSort = movies.reduce(function(acc, curBook){
if(Array.isArray(curBook.genre)){
return {...acc,[curBook.genre[0]]:curBook}
}
else if(curBook.genre){
return {...acc,[curBook.genre]:curBook}
}
return acc
},{})
console.log(genreSort)
`
You;re overwriting your single element for each group every time. You need an array there.
const movies = [{
title: 'Harry Potter',
genre: 'fantasy'
},{
title:'Bridgerton',
genre:'romance'
},{
title: 'Chesnut Man',
genre: 'crime'
},{
title: 'Little Women',
genre: 'romance'
},{
title:'The Mask',
genre: 'comedy'
},{
title:'Holidate',
genre: ['comedy', 'romance']
}];
const genreSort = movies.reduce(function(acc, curBook){
let key = Array.isArray(curBook.genre) ? curBook.genre[0] : curBook.genre
var arr = acc[key] || []
arr.push(curBook);
acc[key] = arr;
return acc
},{})
console.log(genreSort)