THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Array reduce() Method

JavaScript Array Reference JavaScript Array Reference

Example

Get the sum of the numbers in the array:

var numbers = [65, 44, 12, 4];

function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}

The result will be:

125
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The reduce() method reduces the array to a single value.

The reduce() method executes a provided function for each value of the array (from left-to-right).

The return value of the function is stored in an accumulator (result/total).

Note: reduce() does not execute the function for array elements without values.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
reduce() Yes 9.0 3.0 4 10.5

Syntax

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

Parameter Values

Parameter Description
function(total,currentValue, index,arr) Required. A function to be run for each element in the array.
Function arguments:
Argument Description
total Required. The initialValue, or the previously returned value of the function
currentValue Required. The value of the current element
currentIndex Optional. The array index of the current element
arr Optional. The array object the current element belongs to
initialValue Optional. A value to be passed to the function as the initial value

Technical Details

Return Value: A Boolean. Returns true if any of the elements in the array pass the test, otherwise it returns false
JavaScript Version: 1.8

Examples

More Examples

Example

Round all the number is an array, and display the sum:

<button onclick="myFunction()">Try it</button>

<p>Sum of numbers in array: <span id="demo"></span></p>

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

function getSum(total, num) {
    return total + Math.round(num);
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum,0);
}
</script>
Try it Yourself »

JavaScript Array Reference JavaScript Array Reference