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);
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);
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>
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; }