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:
- function(total, currentValue, index, arr): It is the required parameter and is used to run for each element of the array. It contains four parameters which are listed below:
- total: It is a required parameter and used to specify the initialValue or the previously returned value of the function.
- currentValue: It is a required parameter and is used to specify the value of the current element.
- currentIndex: It is an optional parameter and is used to specify the array index of the current element.
- arr: It is an optional parameter and is used to specify the array object the current element belongs to.
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
.
Javascript
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) |
15
Contact Us