javascript
  1. javascript-reduceright

JavaScript reduceRight()

Syntax

The syntax for the reduceRight() method is as follows:

array.reduceRight(callback[, initialValue])
  • callback is a function that is executed on each element in the array.
  • initialValue is an optional parameter that sets the initial value for the accumulator.

Example

Consider the following example:

const numbers = [10, 20, 30];
const sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue);

console.log(sum);

Output:

60


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ReduceRight Function Example</title>
</head>
<body>

<!-- Display the result in this element -->
<div id="result"></div>

<script>
  // Sample array of numbers
  const numbers = [10, 20, 30];

  // Use reduceRight to find the sum of the numbers from right to left
  const sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue);

  // Display the result on the page
  const resultElement = document.getElementById('result');
  resultElement.innerHTML = `<p>Sum of the numbers (from right to left): ${sum}</p>`;
</script>

</body>
</html>
Try Playground

Explanation

The reduceRight() method works similar to the reduce() method, except that it starts from the last element of the array and iterates towards the first element. It takes a callback function as an argument, which is executed on each element in the array and returns a single value as an accumulator. The result of the callback function is then used as the accumulator for the next function call.

Use

The reduceRight() method is useful when you want to reduce an array into a single value, but need to start from the last element of the array. It is commonly used to calculate the total sum of an array, find the maximum or minimum value in an array, or to concatenate all the elements of an array into a single string.

Important Points

  • The reduceRight() method modifies the original array and returns a single value.
  • If the initialValue is not provided, the reduceRight() method will start iterating from the second last element of the array.
  • The callback function takes four parameters: accumulator, currentValue, index, and array.
  • The reduceRight() method works on arrays with a length greater than 0.

Summary

The reduceRight() method in JavaScript is a powerful way to reduce an array into a single value, starting from the last element of the array. It takes a callback function as an argument, which is executed on each element in the array, and returns a single value as an accumulator. It is commonly used to calculate the total sum of an array, find the maximum or minimum value in an array, or to concatenate all the elements of an array into a single string.

Published on: