What is array reduceRight() in Javascript?
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.
Prototype
array.reducRight((accumulator, currentValue, index, array)=>{}, initialValue)
Parameters
-
callbackfn: The callback function that is executed on each of the values in the array.callbackfntakes in 4 additional arguments:accumulator: Theaccumulatorholds the accumulated result of applying thecallbackfnto the list.accumulatoris initialized withinitial Valueif 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. Theindexstarts from if theinital Valueis provided, otherwise, it starts at .array(optional): The array on whichreduce()is called upon.
-
initalValue(optional):initialValueis used as the first value for thereduce()operation. If it is not supplied, then the first value at index is used as theaccumulator.
Return value
reduce() returns the accumulated result of applying the function on each of the elements in the array.
Code
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