Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
js reduce to group on a key's value with duplicates

How can I use .reduce() to group by the value - so if I have the following:

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'
 }
]

I want this :

  {
   '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'}]
  }
   


I tried this but it didn't work:

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It's not a tiny one liner, but it's readable

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 Denunciar

0

What you have is close, but make sure to:

  • spell acc properly
  • keep the previous values in the array with (acc[p.value]||[]).concat(p)
  • provide an initial value, {} as the second arg
arr.reduce((acc,p) => ({ ...acc, [p.value]: (acc[p.value]||[]).concat(p) }), {})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda