The reduceRight() method in JavaScript is similar to the reduce() method, but it reduces the array from right to left instead of left to right. It executes a provided function for each value of the array and accumulates the result, starting from the last element. The reduceRight() method takes two arguments: the reducer function and an optional initial value.
Syntax
array.reduceRight(callback(accumulator, currentValue, index, array), initialValue);
Parameters
Parameters | Descriptions |
---|---|
callback() | A function to execute on each element in the array, taking four arguments:
|
initialValue (Optional) | A value to use as the first argument to the first call of the callback. If no initial value is supplied, the last element in the array will be used as the initial accumulator value and skipped as currentValue. |
Return Value
Return Type | Description |
---|---|
Any | The value that results from the reduction. |
Example 1: Summing Array Values from Right to Left
This code demonstrates how to use the reduceRight() method to calculate the sum of values in an array from right to left.
let Arr = [1, 2, 3, 4, 5]; let sum = Arr.reduceRight( (accumulator, currentValue) => accumulator + currentValue); console.log(sum);
Output:
15
Example 2: Flattening an Array of Arrays from Right to Left
The reduceRight() method can also be used to flatten an array of arrays from right to left.
let Arr = [[1, 2], [3, 4], [5, 6]]; let flattened = Arr.reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue)); console.log(flattened);
Output:
[ 5, 6, 3, 4, 1, 2 ]
Example 3: Using reduceRight() with an Initial Value
You can provide an initial value to reduceRight() as the second argument.
let Arr = [1, 2, 3, 4, 5]; let sum = Arr.reduceRight( (accumulator, currentValue) => accumulator + currentValue, 10); console.log(sum);
Output:
25
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
3 | 12 | 3 | 10.5 | 4 |