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.
callback: It is the callback function that executes over each array element. It undertakes the following arguments:
initialValue: It is an optional argument which uses its supplied value as an accumulator to the initial calling of the callback function.
It reduces a single value as an output.
Points to note:
Let's see some examples to understand better:
Here's a simple implementation of the Array reduceRight() method.Test it Now
But, it is not clear that reduceRight() method is working from right-to-left or right-to-left in the above example.
Here's an implementation which shows the working direction of the reduceRight() method.Test it Now
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.
ExampleTest it Now
We can implement many more examples to understand the working of the method deeply.