Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda