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.

// Create reduce() method from scratch

Array.prototype.myReduce = function(func, init) {
    let accum = init;
    for (let i=0; i<this.length; i++) {
        accum = func(accum,this[i]);
    }
    console.log('total scores: ',accum);
    return accum;
};

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

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

const class1 = [90,98,89,100,100,86,94];
const class2 = [40,65,77,82,80,54,73,63,95,49];
const word = 'parrot'

console.log((class1.myReduce(adder,0)/class1.length).toFixed(2)); // output = 93.86
console.log((class2.myReduce(adder,0)/class2.length).toFixed(2)); // output = 67.8
console.log(((word).split('')).myReduce(removeR,'')); // output = paot


 

Leave a Reply

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