Reduction Methods in Javascript array

Description

Reduction methods iterate over all array items and return one value.

Javascript has two reduction methods:

  • reduce() starts at the first item and continues to the last
  • reduceRight() starts at the last and continues to the first.

They both accpet two arguments:

  • a function to call on each item and
  • an optional initial value upon which the reduction is based.

The function passed into reduce() or reduceRight() accepts four arguments:

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

Value returned from the function is passed in as the first argument for the next item.

Example

You can use the reduce() and reduceRight() method to perform operations such as adding all numbers in an array.


var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
   return prev + cur;//from w  w  w.  j  ava 2s  .  com
});
console.log(sum); //15

var sum = values.reduceRight(function(prev, cur, index, array){
    return prev + cur;
});
console.log(sum); //15

In the code above when calling reduce(), the first time the callback function is executed, prev is 1 and cur is 2; the second time, prev is 3 resulting of adding 1 and 2, and cur is 3 which is the third item in the array.

The first iteration occurs on the second item in the array, so the first argument is the first item in the array and the second argument is the second item in the array.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions