CARVIEW |
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.callbackfn
takes in 4 additional arguments:accumulator
: Theaccumulator
holds the accumulated result of applying thecallbackfn
to the list.accumulator
is initialized withinitial 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. Theindex
starts from 0 if theinital Value
is provided, otherwise, it starts at 1.array
(optional): The array on whichreduce()
is called upon.
-
initalValue
(optional):initialValue
is used as the first value for thereduce()
operation. If it is not supplied, then the first value at index 0 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.
Relevant Answers
Explore Courses
Free Resources