So i have this data structure:
const Array= [
{
court: 'court1',
judge: 'judge1'
},
{
court: 'court1',
judge: 'judge3'
},
{
court: 'court1',
judge: 'judge2'
},
{
court: 'court1',
judge: 'judge1'
},
{
court: 'court2',
judge: 'judge1'
},
{
court: 'court2',
judge: 'judge2'
}
]
and should to modify to like this:
Obj = {
court1: ["judge1", "judge3", "judge2"],
court2: ["judge1", "judge2"]
}
So finally i find some decision and edit myself like this:
let result = Array.reduce((acc, cur) => {
acc[cur.court] = acc[cur.court] || []
if (acc[cur.court].indexOf(cur.judge) === -1) {
acc[cur.court].push(cur.judge)
}
return acc
}, Object.create(null))
console.log(result)
But i try to understand WHY the line acc[cur.court] = acc[cur.court] || []
create a new object like this:
Obj = {
court1: [],
court2: []
}
Can you explain me please? And maybe you know more elegant decision? Thanks!