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

Do 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.