2

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!

dukalis945
  • 25
  • 2

1 Answers1

2

The acc is initially an empty object. Inside the reduce callback, the only properties that are ever assigned to it, with the line acc[cur.court] = acc[cur.court] || [], are arrays, and arrays are truthy.

If a property exists at cur.court, acc[cur.court] || [] will evaluate to that property. Otherwise, it'll evaluate to an empty array. Then, it'll assign the result to acc[cur.court].

A less confusing way of writing it, while doing the same thing, would be:

if (!acc[cur.court]) {
  acc[cur.court] = [];
}

The code looks pretty reasonable already, although I'd prefer using the if statement above, because it looks a bit less confusing.

Another option would be to avoid reduce entirely when the accumulator is always the same object, as some would argue:

const result = {};
for (const { court, judge } of Array) {
  if (!result[court]) {
    result[court] = [];
  }
  result[court].push(judge);
}

(if possible, also change the Array variable name, maybe to arr or something. It's shadowing window.Array, which has potential for confusion and bugs)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320