JavaScript Array reduceRight() MethodThe 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. SyntaxParametercallback: 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. ReturnIt reduces a single value as an output. Points to note:
JavaScript Array reduceRight() Method ExampleLet's see some examples to understand better: Example1 Here's a simple implementation of the Array reduceRight() method. Test it NowOutput: 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. Test it NowOutput: 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 Test it NowOutput: We can implement many more examples to understand the working of the method deeply.
Next TopicJavaScript Array
|