JavaScript - reduce() method

Revision:


Category : array

The reduce() method executes a reducer function for an array element. It returns a single value: the function's accumulated result. It does not execute the function for empty array elements and does not change the original array.

Syntax:

        array.reduce(callbackFn)
        array.reduce(callbackFn, initialValue)
        array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Parameters:

callbackFn, function() : required; a function to be run for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce(). The function is called with the following arguments:

accumulator, total : required; The value resulting from the previous call to callbackFn. On first call, initialValue if specified, otherwise the value of array[0].

currentValue : required; the value of the current element. On first call, the value of array[0] if an initialValue was specified, otherwise the value of array[1].

currentIndex : optional; the index position of currentValue in the array. On first call, 0 if initialValue was specified, otherwise 1.

array : optional; the array "reduce()" was called upon.

initialValue : optional; a value to be passed to the function as the initial value. A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first value in the array as currentValue. If initialValue is not specified, accumulator is initialized to the first value in the array, and callbackFn starts executing with the second value in the array as currentValue. In this case, if the array is empty (so that there's no first value to return as accumulator), an error is thrown.

Examples:

            const array1 = [1, 2, 3, 4];
            // 0 + 1 + 2 + 3 + 4
            const initialValue = 0;
            const sumWithInitial = array1.reduce(
            (accumulator, currentValue) => accumulator + currentValue,
            initialValue
            );
            console.log(sumWithInitial);
            // Expected output: 10
        

Practical examples

example: reduce array to total (=sum).

1/ array: [34, 12, 143, 13, 76]

2/ values: [1, 2, 3, 4, 5]

3/ sum of rounded numbers

4/ reduce array into one number

code:
                <div>
                    <p class="spec">1/ array: [34, 12, 143, 13, 76]</p>
                    <p class="spec" style="margin-left: 4vw;" id="demo01"></p>
                    <p class="spec">2/ values: [1, 2, 3, 4, 5]</p>
                    <p class="spec" style="margin-left: 4vw;" id="demo02"></p>
                    <p class="spec">3/ sum of rounded numbers</p>
                    <p class="spec" id="demo03"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo04"></p>
                    <p class="spec">4/ reduce array into one number</h2>
                    <p class="spec" id="demo05"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo06"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo07"></p>
                </div>
                <script>
                    // 1
                    let total = [34, 12, 143, 13, 76].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
                    document.getElementById("demo01").innerHTML = "total:  " + total;

                    // 2
                    let vals = [1, 2, 3, 4, 5];
                    let sum = vals.reduce((total, next) => {return total + next});
                    document.getElementById("demo02").innerHTML = `The sum of the values is: ${sum}`;

                    // 3
                    const numbers = [15.5, 2.3, 1.1, 4.7];
                    document.getElementById("demo03").innerHTML = "array :" + numbers;
                    function getSum(total, num) {
                        return total + Math.round(num);
                    }
                    document.getElementById("demo04").innerHTML = "sum of rounded numbers:  " + numbers.reduce(getSum, 0);

                    // 4
                    const numbers1 = [1, 2, 3, 4, 5, 6, 8, 10, 12];
                    document.getElementById("demo05").innerHTML = "array :" + numbers1;
                    const sumOfNumbers = numbers1.reduce((accumulator, currentValue)=>{
                    return accumulator + currentValue
                    }, 0)
                    document.getElementById("demo06").innerHTML = "sum of numbers: " + sumOfNumbers;
                        
                    // you can store your reducer function in a variable to make your code neater and more readable
                    const reducerFn = (accumulator, currentValue)=>{
                    return accumulator + currentValue
                    }
                    const sumOfNumbers2 = numbers1.reduce(reducerFn, 0)
                    document.getElementById("demo07").innerHTML = "sum of numbers: " + sumOfNumbers2;
                </script>
            

example: product of values.

1/ values: [1, 2, 3, 4, 5]

2/ values: [10, 20, 30, 40, 50]

code:
                <div>
                    <p class="spec">1/ values: [1, 2, 3, 4, 5]</p>
                    <p class="spec" style="margin-left: 4vw;" id="demo08"></p>
                    <p class="spec">2/ values: [10, 20, 30, 40, 50]</p>
                    <p class="spec" style="margin-left: 4vw;" id="demo08A"></p>
                    <p class="spec" id="demo08B"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo08C"></p>
                    <p class="spec" id="demo08D"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo08E"></p>
                    <p class="spec" id="demo08F"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo08G"></p>
                </div>
                <script>
                    // 1
                    let waarden = [1, 2, 3, 4, 5];
                    let product = waarden.reduce((total, next) => {return total * next});
                    document.getElementById("demo08").innerHTML = `The product of the values is: ${product}`;
        
                    //  2
                    let valeurs = [10, 20, 30, 40, 50];
                    let productA = valeurs.reduce((total, next) => {return total * next});
                    document.getElementById("demo08A").innerHTML = `The product of the values is: ${productA}`;
        
                    // 3
                    function multiply(a, b) {
                        return a * b;
                    }
                    const sampleArray = [1, 2, 3, 4];
                    document.getElementById("demo08B").innerHTML = "3/ sample array: " +  sampleArray;
                    const productB = sampleArray.reduce(multiply, 1);
                    document.getElementById("demo08C").innerHTML = "The product total is: " +  productB;
                    // 4
                                
                    function multiplier(a, b) {
                        return a * b;
                    }
                    const numberArray = [10, 2, 30, 4];
                    document.getElementById("demo08D").innerHTML = "4/ numberArray: " +  numberArray;
                    const productC = numberArray.reduce(multiplier, 1);
                    document.getElementById("demo08E").innerHTML = "The product total is: " +  productC;
                    // 5
                    const thisArray = [10, 220, 410, 634]
                    document.getElementById("demo08F").innerHTML = "5/ this Array: " +  thisArray;
                    const productD = thisArray.reduce((accumulator, element) => {
                    return accumulator * element;
                    }, 1);
                    document.getElementById("demo08G").innerHTML = "The product total is: " +  productD;
                    
                </script>
            

example: min and max values.

1/ values: [1, 2, 3, 4, 5]

code:
                <div>
                    <p class="spec">1/ values: [1, 2, 3, 4, 5]</p>
                    <p class="spec" style="margin-left: 4vw;" id="demo09"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo10"></p>
        
                    <p class="spec"  id="demo10A"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo10B"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo10C"></p>
        
                    <p class="spec"  id="demo10D"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo10E"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo10F"></p>
                </div>
                <script>
                    // 1
                    let values = [1, 2, 3, 4, 5];
                    const [initial] = values;
                    const min = values.reduce((total, next) => Math.min(total, next), initial);
                    const max = values.reduce((total, next) => Math.max(total, next), initial);
                    document.getElementById("demo09").innerHTML = `The minimum of the values is: ${min}`;
                    document.getElementById("demo10").innerHTML = `The maximum of the values is: ${max}`;
                    // 2
        
                    const array_A = [1, 9, 7, 4, 3];
                    document.getElementById("demo10A").innerHTML = "2/ new array: " + array_A;
                    const max_A = array_A.reduce((accumulator, current) => {
                        return accumulator > current ? accumulator : current;
                    });
                    document.getElementById("demo10B").innerHTML = `Maximum number is: ${max_A}`;
                    const min_A = array_A.reduce((accumulator, current) => {
                        return accumulator < current ? accumulator : current;
                    });
                    document.getElementById("demo10C").innerHTML = `Minimum number is: ${min_A}`;
                
                    // 3
                    numbers_1 = [3, 5, 1, 77, 2, 3];
                    document.getElementById("demo10D").innerHTML = "3/ numbers: " + numbers_1;
                    highestNumber = numbers_1.reduce((accumulator, currentValue) => {
                        if (accumulator > currentValue) {
                                return accumulator; 
                        } else return currentValue;
                    });
                    document.getElementById("demo10E").innerHTML = "highest number: " + highestNumber;
                    console.log("Max Number = " + highestNumber)
                    lowestNumber = numbers_1.reduce((accumulator, currentValue) => {
                        if (accumulator > currentValue) {
                                return currentValue; 
                        } else return accumulator;
                    });
                    document.getElementById("demo10F").innerHTML = "lowest number: " + lowestNumber;
                    console.log("Min Number = " + lowestNumber)
                </script>
            

example: average of an array.

code:
                <div>
                    <p id="demo11" class="spec"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo12"></p>
        
                    <p id="demo13" class="spec"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo14"></p> 
        
                    <p class="spec" id="demo15"></p> 
                    
                    <p id="demo13A" class="spec"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo14A"></p> 
                
                    <p id="demo13B" class="spec"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo14B"></p> 
                </div>
                <script>
                    // 1
                    let scores = [89, 76, 47, 95];
                    document.getElementById("demo11").innerHTML = "1/ values to be used for average:  " + scores;
                    let initialValue = 0;
                    let reducer = function (accumulator, item) {
                        return accumulator + item
                    };
                    let total1 = scores.reduce(reducer, initialValue);
                    let average = total1 / scores.length;
                    document.getElementById("demo12").innerHTML = "average :" + average;
                    // 2 
                    const euros = [29.76, 41.85, 46.5, 52.4, 23.3, 34.5];
                    document.getElementById("demo13").innerHTML = "2/ values (euros) to be used for average:  " + euros;
                    const gemiddelde = euros.reduce((totaal, amount, index, array) => {
                    totaal += amount;
                        if( index === array.length-1) { 
                            return totaal/array.length;
                        }else { 
                            return totaal;
                        }
                        });
                    document.getElementById("demo14").innerHTML = "array average: " + gemiddelde;
                    // 3
                    function average1(arr){
                        return arr.reduce((a,b)=>a+b)/arr.length
                        }
                    document.getElementById("demo15").innerHTML = "3/ average of array [1,2,3,4,5]: " + average1([1,2,3,4,5]);
                    //  4
                    const arr_2 = [129, 139, 155, 176];
                    document.getElementById("demo13A").innerHTML = "4/ array for calculating average: " + arr_2;
                    // sum all the elements of the array
                    const sum_2 = arr_2.reduce(function (accumulator, currentValue){
                        return accumulator + currentValue;
                    }, 0);
                    const average_2 = sum_2 / arr_2.length;
                    document.getElementById("demo14A").innerHTML = "average  " + average_2;
                    console.log(average_2);
                    // 5
                    const arr_3 = [1290, 1590, 1950, 2160];
                    document.getElementById("demo13B").innerHTML = "5/ array for calculating average: " + arr_3;
                    const calculateAverage = (arr_3 = []) => {
                        const reducer = (acc, value, index, array_3) => {
                            let val = acc + value;
                            if (index === array_3.length - 1) {
                                return val / array_3.length;
                            };
                            return val;
                        };
                        const res = arr_3.reduce(reducer, 0);
                        return res;
                    };
                    document.getElementById("demo14B").innerHTML = "average: " + calculateAverage(arr_3);
                    console.log(calculateAverage(arr_3));
        
                </script>   
            

example: flatten an array

1/ array = [[0, 1], [2, 3], [4, 5], [5, 6]]

2/ myarrays = [ ["10"], ["11"], ["22"], ["25"], ["13"], ["16"], ["30"], ["34"], ["40"]

3/ nested array = [ [0, 1], [2, 3], [4, 5] ]

code:
                <div>
                    <p class="spec" id="demo16">1/ array = [[0, 1], [2, 3], [4, 5], [5, 6]]</p> 
                    <p class="spec" style="margin-left: 4vw;" id="demo17"></p>

                    <p class="spec" id="demo18">2/ myarrays = [ ["10"], ["11"], ["22"], ["25"], ["13"], ["16"], ["30"], ["34"], ["40"] </p>
                    <p class="spec" style="margin-left: 4vw;" id="demo19"></p>

                    <p class="spec" id="demo18A">3/ nested array = [ [0, 1], [2, 3], [4, 5] ] </p>
                    <p class="spec" style="margin-left: 4vw;" id="demo19A"></p>
                </div>
                <script>
                    //  1
                    let array = [[0, 1], [2, 3], [4, 5], [5, 6]];
                    let flattenedArray = array.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
                    document.getElementById("demo17").innerHTML = "flattened array:  " + flattenedArray;
                    // 2
                    var myarrays = [ ["10"], ["11"], ["22"], ["25"], ["13"], ["16"], ["30"], ["34"], ["40"] ];
                    myarrays = myarrays.reduce(function(a, b){
                        return a.concat(b);
                    }, []);
                    document.getElementById("demo19").innerHTML = "flattened array:" + myarrays; 
                    console.log(myarrays);
                    // 3
                    const nestedArray = [ [0, 1], [2, 3], [4, 5] ];
                    const flattednedArray = nestedArray.reduce((accumulator, currentvalue) => {
                        return accumulator.concat(currentvalue);
                    });
                    document.getElementById("demo19A").innerHTML = "flattened array:" + flattednedArray; 
                    console.log("nested", nestedArray);
                    console.log("flatted", flattednedArray);
                </script>
            

example: create a tally (= count occurences).

code:
                <div>
                    <p class="spec" id="demo20"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo21"></p>
        
                    <p class="spec" id="demo22"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo23"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo24"></p>
        
                    <p class="spec" id="demo25"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo26"></p>
            
                    <p class="spec" id="demo27"></p>
                    <p class="spec" style="margin-left: 4vw;" id="demo28"></p>
                </div>    
                <script>
                    // 1
                    const names = ['John', 'Alice', 'Maria', 'Mir', 'John'];
                    document.getElementById("demo20").textContent = "1/ names:  " + names; 
                    const counts = names.reduce((accumulator, name) => {
                        if (name in accumulator) {
                            accumulator[name] = accumulator[name] + 1;
                        } else {
                            accumulator[name] = 1;
                        }
                        return accumulator;
                    }, {});
        
                    document.getElementById("demo21").innerHTML = "names tally: " + "John: " 
                    + counts['John'] + ";   Alice: " + counts['Alice'] + ";  Maria: " + counts["Maria"]  + "; 
                    Mir: " + counts["Mir"] ;
                    //  2
                    var arr1=[1,2,3,4,5,6,7,8,9,10, 11, 13, 15, 16, 18];
                    document.getElementById("demo22").innerHTML = "2/ array :" + arr1;
                    document.getElementById("demo23").textContent = "count odd numbers: " + 
                    arr1.reduce((a,b) => a+(b%2?1:0),0);
                    document.getElementById("demo24").textContent = "count even numbers: " + 
                    arr1.reduce((a,b) => a+(b%2?0:1),0);
                    // 3
                    const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 
                    'banana', 'cherry', 'orange', 'fig' ];
                    document.getElementById("demo25").innerHTML = "3/ fruitbasket :" + fruitBasket;
                    const count = fruitBasket.reduce( (tally, fruit) => {
                        tally[fruit] = (tally[fruit] || 0) + 1 ;
                        return tally;
                    } , {})
                    document.getElementById("demo26").textContent = "count tally: " +  
                    "banana: " + count['banana'] + ";   cherry: " + count['cherry'] + ";  orange: " 
                    + count["orange"]  + ";  apple: " + count["apple"] + ";  fig: " + count["fig"];
                    
                    //    4
                    const words = ['sky', 'forest', 'wood', 'sky', 'rock', 'cloud', 'sky', 'forest', 'rock', 'sky'];
                    document.getElementById("demo27").innerHTML = "4/ words:  " + words;
                    const tally1 = words.reduce((total, next) => {
                        total[next] = (total[next] || 0) + 1 ;
                        return total;
                    }, {});
                    document.getElementById("demo28").textContent = "count tally: " +  "sky: "
                    + tally1['sky'] + ";  forest: " + tally1['forest'] + ";  wood: " + tally1["wood"]  +
                    ";  rock: " + tally1["rock"] + ";  cloud: " + tally1["cloud"];
                                
                </script>