Javascript Problems – Create my own Array.prototype.reduce() method – myReduce()

In this exercise, I create my own Array.prototype.reduce() method – myReduce().  On line 3, I add a new method to the Array object which takes in a function and an initial value.  Starting on line 5, I loop through the array that calls this method.  The function called is applied to each element, and the array is updated.

My first two outputs on lines 28 and 29 take a list of student grades, uses the myReduce() method to add them into one figure, and then divides that total number by the length of the array to get the actual average.  The first argument in myReduce() is the adder function which will add the array list, and the second argument sets the initial value to 0.  Line 6 of the myReduce() method sets the accumulator to the value returned from the adder function (which is adding the next element in the array to the accumulator).

My second example takes the word ‘parrot’ and runs the function removeR to remove all the ‘r’s from the word.  If removeR discovers an ‘r’, then it returns the accumulator as-is.  However, if the current letter is not ‘r’, then the function adds that letter to the accumulator and returns it.

 

Leave a Reply

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