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

136
Views
seeking a concise way to accumulate values

The following code produces the desired output but is there a more concise way to write it? ie. one liner approaches

const data = [
    { id: '385/72/21', month: 4 },
    { id: '385/72/21', month: 7 },
    { id: '385/72/21', month: 8 },
    { id: '385/72/21', month: 10 },
    { id: '461/80/07', month: 1 },
    { id: '461/80/07', month: 5 },
    { id: '461/80/07', month: 9 }
];

const accumulator = Object.assign({}, ...data.map(o => ({ [o.id]: [] })))
data.forEach(o => accumulator[o.id].push(o.month));
console.log(accumulator);

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

0

const data = [
    { id: '385/72/21', month: 4 },
    { id: '385/72/21', month: 7 },
    { id: '385/72/21', month: 8 },
    { id: '385/72/21', month: 10 },
    { id: '461/80/07', month: 1 },
    { id: '461/80/07', month: 5 },
    { id: '461/80/07', month: 9 }
];

const result = data.reduce((accu, curr) => {
    accu[curr.id] = Array.isArray(accu[curr.id]) ? [...accu[curr.id], curr.month] : [curr.month];
    return accu;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

I prefer using the comma operator instead of spreading over and over again (depending on your dataset you may incur a performance penalty):

console.log(

  data.reduce((acc, {id, month}) =>
    (acc[id] ??= [], acc[id].push(month), acc), {})

);
<script>
const data = [
    { id: '385/72/21', month: 4 },
    { id: '385/72/21', month: 7 },
    { id: '385/72/21', month: 8 },
    { id: '385/72/21', month: 10 },
    { id: '461/80/07', month: 1 },
    { id: '461/80/07', month: 5 },
    { id: '461/80/07', month: 9 }
];
</script>

about 4 years ago · Juan Pablo Isaza Report

0

Another way of using Array.reduce() to get the required output:

const data = [ { id: '385/72/21', month: 4 }, { id: '385/72/21', month: 7 }, { id: '385/72/21', month: 8 }, { id: '385/72/21', month: 10 }, { id: '461/80/07', month: 1 }, { id: '461/80/07', month: 5 }, { id: '461/80/07', month: 9 } ];
const result = data.reduce((acc, { id, month}) => ({ ...acc, [id]: [ ...(acc[id] || []), month ]  }), {})

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!