How to .reduce() Your 99 Problems Into 1 Solution

Again this week, I came across another convenient JavaScript array function known as Array.prototype.reduce(), or just reduce(). This function carries out a method in order to derive a single value from an array of values. It will iterate through the elements of the array and apply the callback function on each of the elements until it gets to the end. Once it has gone through the array, it will return the result of the computation that was performed on the elements of the array.

It is applied to a specific array and receives a function as an argument. Its syntax is on the line below:

myArray.reduce(function(prevValue, currentValue, currentIndex, array), initialValue);

where:

  • "prevValue" is the previously returned value of the function,
  • "currentValue" is the value of the current element,
  • "currentIndex" is the index of the array where the currentValue is,
  • "array" is the array that the currentValue is being read from, and
  • "initialValue" is the value that the function should start with. The prevValue and currentValue arguments are required, but the currentIndex, array, and initialValue parameters are optional.

This is essentially the same as iterating through an array with a loop, like so:

var prevValue = initialValue;

for(let currentIndex=0; currentIndex<array.length; currentIndex++) {
let currentValue = array[currentIndex];
prevValue = function(currentValue);
}

The reduce() function is nice because it only occupies one line, as opposed to the multiple lines it takes to write a loop. This makes your code less cluttered and easier to read. The reduce() function can easily be used to solve problems such as finding the average of all the numbers in an array, finding the longest name in an array, and any other method which involves going through multiple values and applying the same function to each one in order to calculate one resulting value.

For example, let's assume we have an array, known as "digits", that has every number from 1 to 99. We need to find the sum of all the numbers in the array. Let's reduce our 99 problems into 1 solution:

let digits = [1, 2, 3, 4, /*all the way up to 97*/, 98, 99];
let sum = digits.reduce((total, num) => { return total + num }, 0);
console.log(sum);   //This will print out 4,950
//The answer will be 4,955 if you put a 5 as the initial value instead of 0.

Until next week, Pamilerin