Javascript Reduce() Function

The reduce() function of array object apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. Use it for example to perform operation on each element of an array.

Syntax

arr.reduce(callback[, initialValue])

Javascript Reduce() Function Example1

<html>
<head>
<script type="text/javascript">
// Create an array.
var arr = [0, 1, 2, 3, 4, 5];
var value = arr.reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});
document.write(value);
</script>
</head>
<body>
</body>
</html>

This will produce following result

15

Javascript Reduce() Function Example2

<html>
<head>
<script type="text/javascript">
// Create an array.
var arr = [[1, 2], [3, 4], [5, 6]];

var arr_of_arr = arr.reduce(function(a, b) {
  return a.concat(b);
});
document.write(arr_of_arr);
</script>
</head>
<body>
</body>
</html>

This will produce following result

//Now array will contain
[1, 2, 3, 4, 5, 6]