Open In App

What is the use of the Array.reduceRight() method in JavaScript ?

The Array.reduceRight() method in JavaScript is used to reduce the elements of an array from right to left into a single value. It iterates over the array in reverse order, applying a callback function to each element and accumulating a result. This method is similar to Array.reduce(), but it starts the iteration from the last element of the array towards the first.

Syntax: 

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

Parameter: 

Example: Here, we have an array numbers containing numeric values. We use reduceRight() it to calculate the sum of all elements in the array. The callback function takes two arguments: accumulator (initially set to 0) and currentValue. It adds each currentValue to the accumulator, resulting in the cumulative sum. The iteration starts from the last element (5) and proceeds toward the first element (1), resulting in the sum 15.






const numbers = [1, 2, 3, 4, 5];
 
const sum = numbers.reduceRight((accumulator,
    currentValue) => {
    return accumulator + currentValue;
}, 0);
 
console.log(sum); // Output: 15 (5 + 4 + 3 + 2 + 1)

Output
15




Article Tags :