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 }))
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)
What you have is close, but make sure to:
acc properly(acc[p.value]||[]).concat(p){} as the second argarr.reduce((acc,p) => ({ ...acc, [p.value]: (acc[p.value]||[]).concat(p) }), {})