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

181
Views
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 answers
Answer question

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 Report

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 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!