JS Tutorial

Function Reference

Method Reference

  • JS String
  • JS Array
  • JavaScript Array reduce() Method

    The reduce() method is used to apply a function to each element in the array to reduces the array to a single value.

    The reduce() method executes a reducer function on each element of the array (from left-to-right). and return value of the function is stored in an accumulator (result/total).

    Note:The reduce() method does not change the original array.

    Syntax

    array.reduce(callback, initialValue);
    OR
    array.reduce(function(accumulator, currentElement, currentIndex, array), initialValue)
    

    Parameters

    Parameter Description
    function(accumulator, currentElement, currentIndex, array)
    accumulator Required. It is the accumulated value previously returned in the last invocation of the callback—or initialValue.
    currentElement Required. The value of the current element being processed.
    index Optional. The array index of the current element.
    array Optional. The array reduce() was called upon, current elements belongs to.
    initialValue Optional. Initial value passed to the function ,

    Details

    Return : The single value
    Version : ECMAScript 5 (ES5)

    Get the sum of array values using reduce()

    Sum all the values of an array

    var numbersArary = [2,5,6];
    var newResultValue = numbersArary.reduce(testFunc,0)
    
    function testFunc(accumulator,number) {
      return accumulator + number;
    }
    
    console.log(newResultValue);
    //Output : 13
    

    Get the sum of array values by reduce() method using arrow function

    const numbersArary = [2,5,6];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    
    // 2 + 5 + 6
    console.log(numbersArary.reduce(reducer));
    // Output : 13
    
    // 3 + 2 + 5 + 6
    console.log(numbersArary.reduce(reducer, 3));
    // expected output: 16
    

    Sum of values in an object array

    const initialValue = 0;
    const persons = [
      { id: 10, name: 'Vishal Gupta', age:20},
      { id: 11, name: 'Harsendra Singh', age:25},
      { id: 12, name: 'Vipin Katiyar', age:28},
      { id: 13, name: 'Umesh Yadav', age:29}
    ];
    let sumIds = persons.reduce(function (accumulator, currentValue) {
        return accumulator + currentValue.age;
    }, initialValue);
    console.log(sumIds);
    //output : 102