having this array:
const users = [
{ firstName: "lala", lastName: "diaz", age: 23 },
{ firstName: "lela", lastName: "gil", age: 54 },
{ firstName: "lila", lastName: "mendez", age: 43 },
{ firstName: "lula", lastName: "lopez", age: 23 }
]
I have to find the amount of people having different ages.
Output: acc = {23: 2, 54: 1, 43: 1}
The following algorithm works perfectly:
const output = users.reduce((acc, curr) => {
if (acc[curr.age]) ++acc[curr.age]
else acc[curr.age] = 1
return acc
}, {})
I understand that the initial value, acc
is an empty object, but I do not understand the acc[curr.age] notation. I mean: Am I creating an temporal array called arr
, and each element of that array arr
is stored as key value pairs in each iteration of the reducer function? is that the case? how is it done?