Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array
reduceright

What is array reduceRight() in Javascript?

Muhammad Ashir

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: 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 00 if the inital Value is provided, otherwise, it starts at 11.
    • 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 00 is used as the accumulator.

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.

RELATED TAGS

javascript
array
reduceright

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring