• The arrReduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

    The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

    Type Parameters

    • T

      Identifies the type of array elements

    • R = T

    Parameters

    • theArray: ArrayLike<T>

      The array or array like object of elements to be searched.

    • callbackfn: ArrReduceCallbackFn<T, R>

      A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

    • Optional initialValue: T | R

      If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

    Returns R

    The value that results from running the "reducer" callback function to completion over the entire array.

    Example

    const getMax = (a: number, b: number) => Math.max(a, b);

    // callback is invoked for each element in the array starting at index 0
    arrReduce([1, 100], getMax, 50); // 100
    arrReduce([ 50], getMax, 10); // 50

    // callback is invoked once for element at index 1
    arrReduce([1, 100], getMax); // 100

    // callback is not invoked
    arrReduce([ 50], getMax); // 50
    arrReduce([ ], getMax, 1); // 1

    arrReduce([ ], getMax); // throws TypeError

    // Also supports Array like objects
    arrReduce({ length: 2, 0: 1, 1: 100 }, getMax, 50); // 100
    arrReduce({ length: 1, 0: 50 }, getMax, 10); // 50

    // callback is invoked once for element at index 1
    arrReduce({ length: 2, 0: 1, 1: 100 }, getMax); // 100

    // callback is not invoked
    arrReduce({ length: 1, 0: 50 }, getMax); // 50
    arrReduce({ length: 0 }, getMax, 1); // 1
    * ```