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

189
Views
js reduce al grupo en el valor de una clave con duplicados

¿Cómo puedo usar .reduce() para agrupar por el valor? Entonces, si tengo lo siguiente:

 const arr = [ { id: 1, value: 'abc', othervalue: '123' }, { id: 2, value: 'def', othervalue: '123' }, { id: 3, value: 'def', othervalue: '123' }, { id: 4, value: 'ghi', othervalue: '123' } ]

Quiero esto :

 { 'abc' : [{id:1, value:'abc', othervalue: '123'}] 'def' : [{id:2, value:'def', othervalue: '123'}, {id:3, value:'def', othervalue:'123'}], 'ghi' : [{id:4, value:'ghi', othervalue: '123'}] }

Intenté esto pero no funcionó:

arr.reduce( (acc,p) => ({...acc, [p.value]:p }))

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

0

No es un trazador de líneas pequeño, pero es legible

 const arr = [{ id: 1, value: 'abc', othervalue: '123' }, { id: 2, value: 'def', othervalue: '123' }, { id: 3, value: 'def', othervalue: '123' }, { id: 4, value: 'ghi', othervalue: '123' } ] let grouped = arr.reduce((b, a) => { b[a.value] = b[a.value] || []; b[a.value].push(a); return b }, {}) console.log(grouped)

about 4 years ago · Juan Pablo Isaza Report

0

Lo que tienes está cerca, pero asegúrate de:

  • acc correctamente
  • mantener los valores anteriores en la matriz con (acc[p.value]||[]).concat(p)
  • proporcione un valor inicial, {} como el segundo argumento
 arr.reduce((acc,p) => ({ ...acc, [p.value]: (acc[p.value]||[]).concat(p) }), {})
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!