Javascript Reduce Method

I have been studying the reduce() method in Javascript, which can be used to distill an array down to a single item (or multiple items, but less than the number in the original array).  By contrast, the map() method will modify elements in an array,  but will return an array of the same length, or same number of items.

Below, I have a function to average grades using the reduce method. The “0 “on line 8 sets the initial value of “a” (the accumulator) as 0, and indicates that it will return a number.

In the previous example, I call the reduce method from inside the function.  But I re-wrote this using a functional programming style.  Below I have a simple function to add two numbers.  The reduce() method calls the adder function as the first argument and the initial value of “0” as the second argument.

Below is another example using the reduce() method.  Here the object is to remove all ‘r’s from a word.  In this example, I am removing some elements from the array (but not all), and returning a string as specified by the empty string on line 13.

 

Leave a Reply

Your email address will not be published. Required fields are marked *