Hi,
I was looking over the cash register guide because I got stuck on how to convert the input array of cid (cash in drawer) into an object. However, after looking at the guide one part that I don’t fully understand what it’s doing is the part where it’s using the reduce() method to convert the cid to an object.
Could someone help walk me through exactly what this code is doing?
// Transform CID array into drawer object
var register = cid.reduce(
function(acc, curr) {
acc.total += curr[1];
acc[curr[0]] = curr[1];
return acc;
},
{ total: 0 }
);
Just to clarify the parts I do understand, I understand that the new object is called register, and that the object is being created by performing the reduce method on the cid input. I’m not sure on this, but I believe that since a second function is being used within the reduce method, that this second function is taking the denomination and quantity of each value from the sub-arrays of the cid array. acc.total += curr[1] is creating a new related object key value where acc is the denomination in the cid sub-array and curr is the value attached to it in cid, but now converted to a key index pair in our register object… but acc[curr[0]] = curr[1] – I have no clue what role this plays in creating the new object. This solution seems really elegant, but it’s possible I’m completely misunderstanding it all together…
Here is the complete guide for reference where I got this code snippet:
Here is the challenge:
In short, I think this seems like a really useful way to utilize the reduce method and I’d like to be able to add it to my toolbelt in the future. Thanks in advance for any guidance!