How to apply a function simultaneously against two values of the array from left-to-right?


Use the reduce() method in JavaScript to apply a function simultaneously against two values of the array from left-to-right as to reduce it to a single value.

The following are the parameters −

  • callback − Function to execute on each value in the array.
  • initialValue − Object to use as the first argument to the first call of the callback.

Example

You can try to run the following code to learn how to work with reduce() method in JavaScript −

<html>
   <head>
      <title>JavaScript Array reduce Method</title>
   </head>

   <body>
      <script>
         if (!Array.prototype.reduce) {
            Array.prototype.reduce = function(fun /*, initial*/) {
               var len = this.length;
               if (typeof fun != "function")
               throw new TypeError();
               
               // no value to return if no initial value and an empty array
               if (len == 0 && arguments.length == 1)
               throw new TypeError();
               var i = 0;
               
               if (arguments.length >= 2) {
                  var rv = arguments[1];
               } else {
                  do {
                     if (i in this) {
                        rv = this[i++];
                        break;
                     }
                     // if array contains no values, no initial value to return
                     if (++i >= len)
                     throw new TypeError();
                  }
                  while (true);
               }
               for (; i < len; i++) {
                  if (i in this)
                  rv = fun.call(null, rv, this[i], i, this);
               }
               return rv;
            };
         }
         var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
         document.write("total is : " + total );
      </script>
   </body>
</html>

Updated on: 23-Jun-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements