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

119
Views
Ordenar JavaScript con reducir

En mi matriz de películas con función de reducción, estoy tratando de hacer que el género del libro sea una identificación y si el libro tiene más de un género, el primero debe usarse como identificación. El código que escribí no funciona como debería. ¿Qué está mal con mi código y cómo puedo hacer que funcione de la manera correcta?

 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

Está sobrescribiendo su único elemento para cada grupo cada vez. Necesitas una matriz allí.

 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!