The Array.reduceRight()
method is a built-in JavaScript function that processes each element of an array from right to left (starting from the last element to the first) and reduces it to a single output value.
Syntax
arr.reduceRight(callback(accumulator, currentValue, index, array), initialValue);
Parameters
Parameter | Description |
---|---|
callback | (Required) A function to execute on each element in the array. |
accumulator | (Required in callback ) The accumulated result from previous callback executions. |
currentValue | (Required in callback ) The current element being processed. |
index | (Optional in callback ) The index of the current element being processed. |
array | (Optional in callback ) The array reduceRight() is being applied on. |
initialValue | (Optional) A value to use as the initial accumulator . If not provided, the last element of the array is used. |
Return Value
The reduceRight()
method returns the final accumulated value after iterating through all elements of the array from right to left.
Example 1: Concatenating Strings in Reverse Order
let words = ['world', ' ', 'hello']; let result = words.reduceRight((accumulator, currentValue) => accumulator + currentValue, ''); console.log(result); // Output: 'hello world'
Example 2: Summing Array Elements
let arr = [1, 2, 3, 4]; let sum = arr.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 10
Example 3: Flattening a Nested Array in Reverse Order
let arr = [[5, 6], [3, 4], [1, 2]]; let flatArray = arr.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue), []); console.log(flatArray); // Output: [5, 6, 3, 4, 1, 2]
Example 4: Using reduceRight()
Without an Initial Value
let numbers = [10, 20, 30]; let result = numbers.reduceRight((accumulator, currentValue) => accumulator - currentValue); console.log(result); // Output: 0
Supported Browsers
Browser | Support |
---|---|
Chrome | 3+ |
Firefox | 3+ |
Safari | 4+ |
Edge | 12+ |
Opera | 10.5+ |
Internet Explorer | 9+ |