Array reduce()

In this chapter you will learn:

  1. How to reduce array to a value

Array reduce()

reduce() is reduction method. reduce() iterates all items and build up a value for return. reduce() starts at the first item and traveling toward the last.

reduce() accepts two arguments:

  • a function to call on each item
  • an optional initial value

The function passed into reduce() accepts four arguments:

  • the previous value,
  • the current value,
  • the item's index,
  • the array object.

The returned value from the function is passed in as the first argument for the next item. The first iteration occurs on the second item in the array.

<!DOCTYPE html><!--from   j  a va 2  s.  c  o m-->
<html>
<head>
    <script type="text/javascript">
        var values = [1,2,3,4,5]; 
        
        var sum = values.reduce(function(prev, cur, index, array){
            return prev + cur; 
        }); 
        
        document.writeln(sum); //15 
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to reduce a Javascript array from the end
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()