JavaScript(JS) array method - reduceright
The reduceRight()
method is similar to the reduce()
method, but it executes the provided function on each element of the array from right to left. The function takes two arguments: an accumulator and the current value. The reduceRight()
method returns the final value of the accumulator.
Here's an example of how to use the reduceRight()
method:
let words = ["foo", "bar", "baz"]; let result = words.reduceRight(function(accumulator, currentValue) { return accumulator + " " + currentValue; }); console.log(result); // "baz bar foo"
In this example, we have an array words
containing the elements ["foo", "bar", "baz"]
. We use the reduceRight()
method to concatenate all the elements in the words
array, starting from the right.
The reduceRight()
method takes a function as an argument, which is executed on each element of the array from right to left. The function takes two arguments: an accumulator and the current value. In this example, we start with an empty string as the initial value of the accumulator, and concatenate the current value of the array to it with a space in between. The returned value becomes the new value of the accumulator for the next iteration.
After all the iterations are completed, the reduceRight()
method returns the final value of the accumulator, which is the concatenated string of all the elements in the array, starting from the right. We store the final concatenated string value in the variable result
, and log it to the console.