Array.reduceRight()

The Array.reduceRight() method in JavaScript is used to apply a function to each element of an array (from right to left) to reduce it to a single value. This is the reverse of the Array.reduce() method, which processes elements from left to right.

Syntax

</>
Copy
reduceRight(callbackFn)
reduceRight(callbackFn, initialValue)

Parameters

ParameterDescription
callbackFnA function to execute on each element in the array. It takes four arguments: accumulator, currentValue, currentIndex, and array.
initialValue (Optional)The value to use as the first argument to the first call of callbackFn. If not provided, the last element of the array is used as the initial accumulator value.

Return Value

The reduceRight() method returns the single value that results from applying the function to all array elements, starting from the rightmost element.


Examples

1. Summing Array Elements from Right to Left

This example demonstrates how to use reduceRight() to calculate the sum of array elements, starting from the rightmost element.

</>
Copy
const numbers = [1, 2, 3, 4];

const sum = numbers.reduceRight((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0);

console.log(sum);

Output

10
  1. The initial value of accumulator is 0 (provided as initialValue).
  2. Each element is added to the accumulator, starting from the last element (4 + 3 + 2 + 1).

2. Reversing a String

You can use reduceRight() to reverse the characters of a string by splitting it into an array.

</>
Copy
const str = "hello";

const reversed = str.split('').reduceRight((accumulator, currentValue) => {
    return accumulator + currentValue;
}, '');

console.log(reversed);

Output

olleh

Each character is appended to the accumulator in reverse order, resulting in the reversed string.

3. Flattening a Nested Array

The reduceRight() method can be used to flatten a nested array by processing elements from right to left.

</>
Copy
const nestedArray = [[0, 1], [2, 3], [4, 5]];

const flattened = nestedArray.reduceRight((accumulator, currentValue) => {
    return accumulator.concat(currentValue);
}, []);

console.log(flattened);

Output

[4, 5, 2, 3, 0, 1]

The elements are concatenated from the rightmost array to the leftmost array, flattening the array.

4. Calculating a Factorial

Use reduceRight() to calculate the factorial of a number by multiplying array elements.

</>
Copy
const numbers = [1, 2, 3, 4];

const factorial = numbers.reduceRight((accumulator, currentValue) => {
    return accumulator * currentValue;
}, 1);

console.log(factorial);

Output

24

The method multiplies each element of the array, starting from the last, to compute the factorial.