Plenty Left explainer

#1

Aim of the puzzle: Use the .reduce() array method to calculate the remaining balance on a gift card.
Walk through of solution: In this puzzle, you’ll use the reduce method to subtract each number in an array of numbers from a gift card.

.reduce() can be one of the trickiest array methods to learn, so let’s take a close look at how it works in this puzzle.

let giftCard = 100;
let prices = [11.16, 5.02, 5.29, 6.14];

This declares a variable giftCard and sets its value to 100, as well as the array prices, each element being a number.

let remaining = prices.reduce((balance, current) => {
    return balance - current;
}, giftCard);

.reduce() uses 2 arguments: a callback function, and a starting value. The callback function also uses 2 parameters: the total value so far, and the current value.

In this puzzle, the 1st argument of .reduce() is the callback function:

(balance, current) => {
  return balance - current;
}

In this function, balance is the accumulator, and remembers the total value being calculated as reduce iterates (loops) through the array. current represents the current array element as reduce iterates.

return balance - current subtracts the current array element from the total value being calculated.

The 2nd argument of .reduce() is a starting value to use for balance in the callback function. In this case, giftCard is used as the argument, to set the balance to 100. If no 2nd argument is given to .reduce(), the 1st element in the array is automatically used to set the starting value.

The resulting value after the array has been reduced is saved to the variable remaining.

Let’s look at how this value is calculated:

Because giftCard has been used as the 2nd argument for .reduce(), the initial value of balance is set to 100. When .reduce() looks at 11.16, the first element in prices, it calculates 100 - 11.16, which is 88.84.

Next, .reduce() moves to the next number in the array, 5.02, and calculates 88.84 - 5.02, which is 83.82.

For the next iteration, it calculates 83.82 - 5.29, which returns 78.53.
For the last element in prices, it calculates 78.53 - 6.14, which returns 72.39.

This final value, 72.39, is then returned to the variable remaining.

Whew!

Sample code solution:

let giftCard = 100;
let prices = [11.16, 5.02, 5.29, 6.14];
let remaining = prices.reduce((balance, current) => {
    return balance - current;
}, giftCard);
console.log(remaining);

Javascript Concepts: Arrays, Array Methods, .reduce(), Iteration, console.log

0 Likes