I just can't understand this concept in the function below:
acc[line[0]]
I really can't get my head around that piece of code, how come it is not be an error and works perfectly? How do you interpret it in English words? In my head it is an empty object acc {} at its first iteration and according to the piece of code is trying to access the iterated line at its first value [0]. How come it works without the need of inverted commas as well? And how does line[0] ended up to be the values of the object?
Here is the full code:
let output = [["mark johansson", "waffle iron", "80", "2"],
["mark johansson", "blender", "200", "1"],
["mark johansson", "knife", "10", "4"],
["Nikita Smith", "waffle iron", "80", "1"],
["Nikita Smith", "knife", "10", "2"],
["Nikita Smith", "pot", "20", "3"]]
let result =output.reduce((acc,line)=>{
acc[line[0]] = acc[line[0]] || []
acc[line[0]].push({
name: line[1],
price: line[2],
quant: line[3]
})
return acc
},{})
console.log(JSON.stringify(result,null,1))
{
"mark johansson": [
{
"name": "waffle iron",
"price": "80",
"quant": "2"
},
{
"name": "blender",
"price": "200",
"quant": "1"
},
{
"name": "knife",
"price": "10",
"quant": "4"
}
],
"Nikita Smith": [
{
"name": "waffle iron",
"price": "80",
"quant": "1"
},
{
"name": "knife",
"price": "10",
"quant": "2"
},
{
"name": "pot",
"price": "20",
"quant": "3"
}
]
}