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.

function grader(scores) {
    
    let sum = 0
   
    OPTION 2 - REDUCE METHOD
    sum = scores.reduce(function(a,b) {
         return a+b;
    }, 0);
    
    let avg = Math.round(sum / scores.length);
    console.log(avg, scores);    
    return avg;
}
 
grader([90,98,89,100,100,86,94]); // output = 94
grader([40,65,77,82,80,54,73,63,95,49]); // output = 68

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.

function adder(a,b) {
    return a+b;
}

const arr = [40,65,77,82,80,54,73,63,95,49];
const output = Math.round(arr.reduce(adder,0)/arr.length);
console.log(output); // output = 68

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.

// remove the 'r's
const word = 'parrot';
const arr = word.split(''); // ['p', 'a', 'r', 'r', 'o', 't']

function combiner(a,b) {
    if (b ==='r') {
        return a;
    } else {
        return a+b;
    }    
}

const output = arr.reduce(combiner, '');
console.log(output); //output = 'paot';

 

Leave a Reply

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