Need help with Exact Change Challenge


I’m doing Exact Change challenge in advance alogorithm section. but I’m having problems understanding this method. which I got from the “get hint” section. freeCodeCamp Algorithm Challenge Guide: Exact Change

var change_arr = denom.reduce(function(acc, curr) {
    var value = 0;
    // While there is still money of this type in the drawer
    // And while the denomination is larger than the change reminaing
    while (register[] > 0 && change >= curr.val) {
      change -= curr.val;
      register[] -= curr.val;
      value += curr.val;
      // Round change to the nearest hundreth deals with precision errors
      change = Math.round(change * 100) / 100;
    // Add this denomination to the output only if any was used.
    if (value > 0) {
        acc.push([, value ]);
    return acc; // Return the current Change Array
  }, []); // Initial value of empty array for reduce

inside the loop, how does the function knows what and curr.value is comparing to 0. there are many in the array. Or does it start from the biggest value in register and start coming down?


.reduce() goes through array’s values one-by-one, starting from the beginning of the array.

So on first loop curr is { name: 'ONE HUNDRED', val: 100.00}, on second { name: 'TWENTY', val: 20.00} etc.



and acc? is it the return value… the array to be returned? thanks


acc is accumulator. It’s a value that holds (accumulates) result of reduce. Last parameter in .reduce() is initial value (in this case empty array).