reduceRight()
is a higher-order function that accumulates or reduces all the values in an array to a single value through the application of a binary function to each of the values, starting from right to left.
reduceRight()
is useful when the order of operation on the array does matter. However, if the operation is commutative, then one may simply use the reduce()
function instead.
array.reducRight((accumulator, currentValue, index, array)=>{}, initialValue)
callbackfn
: The callback function that is executed on each of the values in the array. callbackfn
takes in 4 additional arguments:
accumulator
: The accumulator
holds the accumulated result of applying the callbackfn
to the list. accumulator
is initialized with initial Value
if an initial value is supplied.current value
: The current value being processed in the array.index
(optional): The index of the current value being processed. The index
starts from if the inital Value
is provided, otherwise, it starts at .array
(optional): The array on which reduce()
is called upon.initalValue
(optional): initialValue
is used as the first value for the reduce()
operation. If it is not supplied, then the first value at index is used as the accumulator
.
reduce()
returns the accumulated result of applying the function on each of the elements in the array.
const numbers = [1 ,2 ,3]const product1 = numbers.reduce((x, y) => x / y);const product2 = numbers.reduceRight((x, y) => x / y);console.log(product1, product2)
Here, we demonstrate the difference in the reduce()
and reduceRight()
functions. Since we used the division operation, which is non-commutative, the order of operation matters.
The reduce()
function applies the division function from left to right while the reduceRight()
operation goes from right to left, which gives a different result.
Free Resources