Reduction and Location Methods : reduce

Reduction and Location Methods (see the eBook for further detail).

The method reduce( ) allows a callback function with up to four arguments:

a)      previousValue – The value from the previous call to the callback function.

b)      currentValue – the value of the element at current iteration (position).

c)      Optional current index or location of the object being traverse. You can exclude the index as a parameter, or included it if you need it for your script.

Let’s look at an example.

We are going to declare an array with even numbers. Then we will declare a variable to store the result of multiplying all numbers of the array using reduce( ).

1-      Declare array qaz:

var qaz = [2,4,6,8];

2-      Declare a variable addQAZ and assign qaz to it, where both left and right values are multiplied by one another, using reduce( ):

 var addQAZ = qaz.reduce(function (previousValue, currentValue, index) {

   return previousValue * currentValue;

 });

 // call the variable addQAZ:

 addQAZ;

3-      Call addQAZ; // returns 384.

On the first iteration, previousValue is 2 (first element) and the currentValue is 4 (second element), and so on.

However, if we had included the initValue, which would go here: }, init); the previousValue would have started at the initValue given, and the currentValue would have started at the first element’s value instead of at the second’s, resulting in a totally different output since the initValue value would have influenced the operation at hand. See the next example:

4-      For example, let’s declare another variable using the same script as before but giving reduce( ) an initValue of 10:

 var addQAZ2 = qaz.reduce(function (previousValue, currentValue, index) {

   return previousValue * currentValue;

 }, 10);

 // call the variable addQAZ2:

 addQAZ2;

5-      Call addQAZ2; // returns 3840. A big difference from before.

For further information as well as all the other methods see my eBook
JavaScript Objects, Functions and arrays Explained.

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s