Cash Register problem -- using the reduce method to convert array to object

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:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register

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!

3 Likes

Hi,
As you know cid is 2d array. where curr[0] is holding the name of the denom and curr[1] is holding its value. So the within the reduce function acc acts as a temp object within the function. where acc.total stores the total value of all the denom present in the drawer and now the second part

This line of code keeps adding denom to the object which are done adding to the total and evaluates as acc.[curr[0] = PENNY]= [curr[1]= 1.01].

To get a better understanding you could even copy the whole code and vizualize it here http://www.pythontutor.com/visualize.html#mode=edit

Hope this helps. Happy Coding

1 Like

It’s going to take me a minute to fully interalize all of this. I didn’t know you could create temporary arguments as objects that have not been defined outside of the function. That’s a totally wild concept to me. Thanks for taking the time to respond! I think if I spend a little time playing with this I can implement it. (also, that’s a nice code execution tool you linked, thx for sharing)

2 Likes