JavaScript Array reduceRight() Method
The reduceRight() method reduces the given array elements into a single value by executing a reducer function. The reducer() function is applied against the accumulator and reduces all the elements from right to left.
Syntax
Parameter
callback: It is the callback function that executes over each array element. It undertakes the following arguments:
- accumulator: It accumulates the initialValue or previously returned values by the callback function.
- currentValue: It holds the current array element in process.
- currentIndex: It is optional. It holds the current value’s index, being in process.
- array: It is optional. It is the source array to which the elements belong.
initialValue: It is an optional argument which uses its supplied value as an accumulator to the initial calling of the callback function.
Return
It reduces a single value as an output.
Points to note:
- When we invoke the callback function for the first time, the accumulator and currentValue can be one of the two values.
- When we provide the initialValue in the function, the accumulator will hold the value of the initialValue, and currentValue will hold the last element of the array.
- When no initialValue is supplied, then accumulator will hold the last array element, and currentValue will hold the second-last array element.
- When an empty array is present with no initialValue, it will throw an error known as TypeError.
- When it’s an array of one element with no initialValue or an empty array with an initialValue, that element will be returned without invoking the callback function.
JavaScript Array reduceRight() Method Example
Let’s see some examples to understand better:
Example1
Here’s a simple implementation of the Array reduceRight() method.
Output:
But, it is not clear that reduceRight() method is working from right-to-left or right-to-left in the above example.
Example2
Here’s an implementation which shows the working direction of the reduceRight() method.
Output:
Thus, it is clear from the above output that reduceRight() works from right-to-left.
Although both reduceRight() and reduce() methods reduce the array elements into a single value, there is a difference between them. The reduce() method reduces the array elements from the left index position to the right. On the other hand, the reduceRight() method reduces the array elements from the right index position towards left.
Let’s see the below implementation to understand better.
Example
Output:
We can implement many more examples to understand the working of the method deeply.