The reduceRight() method of the Array class in JavaScript executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.
There are 2 variations for the syntax of Array.reduceRight() method. They are:
reduceRight(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to execute on each element in the array. It takes four arguments: accumulator, currentValue, currentIndex, and array. |
This method executes the callback function on each element of the array (from right to left) without an initial value, to reduce it to a single value.
Returns value of type Any
.
reduceRight(callbackFn, initialValue)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to execute on each element in the array. It takes four arguments: accumulator, currentValue, currentIndex, and array. |
initialValue | optional | A value to use as the first argument to the first call of the callback. |
This method executes the callback function on each element of the array (from right to left) with the specified initial value, to reduce it to a single value.
Returns value of type Any
.
In JavaScript, we can use the reduceRight() method to concatenate all strings in an array in reverse order.
For example,
const strArr = ['Hello', ' ', 'world', '!'];
const concat = (accumulator, currentValue) => accumulator + currentValue;
const message = strArr.reduceRight(concat);
console.log(message);
!world Hello
We can use the reduceRight() method to sum the values of an array from right to left.
For example,
const arr = [1, 2, 3, 4, 5];
const sum = (accumulator, currentValue) => accumulator + currentValue;
const total = arr.reduceRight(sum);
console.log(total);
15
We can use the reduceRight() method with an initial value to multiply the values in an array from right to left.
For example,
const arr = [1, 2, 3, 4];
const multiply = (accumulator, currentValue) => accumulator * currentValue;
const product = arr.reduceRight(multiply, 2);
console.log(product);
48
In this JavaScript tutorial, we learned about reduceRight() method of Array: the syntax and few working examples with output and detailed explanation for each example.