Skip to content

Instantly share code, notes, and snippets.

@aspitz1
Last active August 24, 2022 15:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save aspitz1/7dac1b6aadb9c8f829a1c99a39c6b408 to your computer and use it in GitHub Desktop.
Save aspitz1/7dac1b6aadb9c8f829a1c99a39c6b408 to your computer and use it in GitHub Desktop.
Presentation on Array.prototype.reduce()

Array.prototype.reduce()

The reduce() array prototype method uses a user supplied accumulator to calculate all element values into a single value. The call back function will most commonly take in arguments of accumulator, currentValue, where the accumulator is the user supplied value and the currentValue is the value of the array index position that is currently being iterated through. The call back function can also take in index and array where index is the index position of the array currently being iterated through and array is the value of the full array.

The final syntax will look something like this most of the time:

array.reduce((accumulator, variable) => {
   statement;
   return accumulator; 
 }, accumulatorStartingValue);

The full syntax of the arguments for the call back function looks like this:

array.reduce((accumulator, variable, index, array) => {
   /*...*/
   return accumulator;
 }, accumulatorStartingValue);

If the user does not provide a value for the accumulator the value will default to be the value of the array at position 0. The user provided value for the accumulator can be a number, string or even something like an empty array or object. The accumulator is mutated, or not, through every iteration depending on the statement provided by the user. There is not a default return value for reduce(). The .reduce() method does not mutate the array it is being called on, but the user could mutate the array in the code provided in the callback function. With that in mind the user must remember to include a return statement.

Quick Note

The reduce() method can be a bit tricky for people that are new to iterator methods. The most straight forward use for reduce() is to iterate over an array of numbers. However, reduce() can be a bit of a Swiss army knife of iterator methods. It may be best to practice with the more straight forward uses prior to exploring the more abstract uses to get a good handle on the functionality of reduce().

Examples

The most straight forward use for reduce() is to use it to iterate over an array of numbers. Here is an example of reduce() being used to add up all the numbers in the array. In the first example an initial value for the accumulator will not be provided to demonstrate how reduce() defaults to the value of the first position in the array. This does not mean the first value is added to the first value. This is because the itreation starts at position 1 of the array using position 0 as the first value. In this example you will see that the return of reduce() is indeed the total of the array without providing a initial value for the accumulator:

const numbers = [3, 8, 9, 1]; // total is 21

const numbersTotal = numbers.reduce((accumulator, number) => {
 return accumulator + number;
 
}); // expected return 21

If you specify the accumulator, the value will start at the value specified. Here -3 is used to show that the total return is 3 less then the return of the previous example:

const numbers = [3, 8, 9, 1]; // total is 21

const numbersTotalSub3 = numbers.reduce((accumulator, number) => {
 return accumulator + number;
 
}, -3); // expected return 18 

The reduce() method could also be used to find the largest (or smallest) number in an array by providing a conditional. Here we will also provide a value for the accumulator of 0:

const numbers = [3, 8, 9, 1]; // largest number is 9

const biggestNumber = numbers.reduce((accumulator, number) => {
 if (number > accumulator) {
   return number;
 } else {
   return accumulator;
 };
 
}, 0); // expected return 9

Less Straight Forward Uses

The reduce() method can be used to do something like interpolate strings together. Here we will not provide a accumulator value, and the value will start as the string in position 0 of the array:

const wordsForYouAreGreat = ['You', 'are', 'great'];

const youAreGreat = wordsForYouAreGreat.reduce((accumulator, word) => {
 return accumulator += ` ${word}`;
 
}); // expected return 'You are great'

Here is an example using reduce() to transform an array into an object. Utilizing the spread operator, we can add on to the empty object provided as the value for the accumulator through every iteration. The index argument will also be used to make a unique key for each key value pair by combining it with a string inside bracket notation:

const animals = ['cat', 'dog', 'fish'];

let housePets = animals.reduce((emptyObject, pet, index) => {
return {...emptyObject, ['animal' + index]: pet};

}, {}); // expected return { animal0: 'cat', animal1: 'dog', animal2: 'fish' }

Conclusion

The reduce() method is extremely versatile. Because of this it can be a challenging iterator to work with. Start with learning the basics of reduce() and soon the user may find themselves finding uses for reduce() in unexpected places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment