Skip to content

Reduce() function in JavaScript | Example code

  • by

JavaScript reduce() function is used with Array to execute a reducer function for the array elements. It returns a single value: the function’s accumulated result.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

The reduce() does not change the original array.

Example Reduce() function in JavaScript

Simple example code Sum of All Values of Array.

<!DOCTYPE html>
<html>
<body>

  <script>
    const numbers = [1, 2, 3, 4, 5];

    function sum_reducer(accumulator, currentValue) {
      return accumulator + currentValue;
    }

    let sum = numbers.reduce(sum_reducer);
    console.log(sum);

    // using arrow function
    let summation = numbers.reduce(
      (accumulator, currentValue) => accumulator + currentValue
      );

    console.log(summation);
  </script>

</body>
</html> 

Output:

Reduce() function in JavaScript

Round all the numbers and display the sum:

  <script>
   const numbers = [15.5, 2.3, 1.1, 4.7];

   console.log(numbers.reduce(getSum, 0));

    function getSum(total, num) {
      return total + Math.round(num);
    }
  </script>

Output: 24

Find the maximum value in an array:

const arr = [3, 6, 2, 8, 1, 9];
const max = arr.reduce((accumulator, currentValue) => {
  if (currentValue > accumulator) {
    return currentValue;
  } else {
    return accumulator;
  }
});
console.log(max); // Output: 9

Comment if you have any doubts or suggestions on this JS reduce topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading