Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
JavaScript sort with reduce

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)

`

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!