Javascript - Array reduceRight() Method

The reduceRight() method reduces the array to a single value from position of length-1 to 0.

Description

The reduceRight() method reduces the array to a single value from position of length-1 to 0.

The reduceRight() method executes a function for each value of the array from end to start.

The return value of the function is stored in an accumulator value.

The reduceRight() does not run the function for array elements without values.

Syntax

array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)

Parameter Values

Parameter Require Description
function(total, currentValue, currentIndex, arr) Required. A function to be run for each element in the array.
initialValue Optional. A value to be passed to the function as the initial value

function(total, currentValue, currentIndex, arr)

Argument Require Description
total Required. The initialValue, or the previously returned value of the function
currentValue Required. The value of the current element
currentIndex Optional. The index of the current array element
arr Optional. The array object the current element belongs to

Return

Returns the accumulated result from the last call of the callback function

Example

Get the sum of the numbers in the array:

Demo

var numbers = [6, 4, 2, 3];

function getSum(total, num) {
    return total + num;
}
console.log( numbers.reduceRight(getSum));

//Subtract the numbers, right-to-left, and display the sum:

var numbers = [2, 45, 30, 100];

function getSum1(total, num) {
    return total - num;
}
console.log( numbers.reduceRight(getSum1));

Result