reduceRight()
, allows you to perform a function on each element of the array from right to left, accumulating a single output value. This article delves into the intricacies of reduceRight()
with clear examples and hardcoded values to enhance understanding.
What is reduceRight()?
The reduceRight()
method in JavaScript executes a provided callback function once for each element present in the array, from right to left, and accumulates the result into a single value. It takes in a callback function and an optional initial value as arguments.
Syntax:
array.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
callback
: A function to execute on each element in the array.accumulator
: The accumulator accumulates the callback’s return values.currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed in the array.array
(optional): The arrayreduceRight()
was called upon.initialValue
(optional): A value to use as the first argument to the first call of the callback function.
Examples
Let’s explore some practical examples to understand reduceRight()
better:
Example 1: Concatenating Strings
const words = ['hello', 'world', 'this', 'is', 'JavaScript'];
const concatenatedString = words.reduceRight((accumulator, currentValue) => {
return accumulator + ' ' + currentValue;
});
console.log(concatenatedString);
Output:
JavaScript is this world hello
Example 2: Summing Array Elements
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduceRight((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum);
Output:
15
Example 3: Flattening an Array of Arrays
const arrays = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = arrays.reduceRight((accumulator, currentValue) => {
return accumulator.concat(currentValue);
}, []);
console.log(flattenedArray);
Output:
[5, 6, 3, 4, 1, 2]