CodingBison

Arrays provide several methods that handle the array as a whole and accept a callback function as an argument. These methods are: forEach(), map(), filter(), every(), some(), reduce(), and reduceRight().

 varArray.forEach(callbackFunc);
 var newVarArray = varArray.map(callbackFunc);
 var newVarArray = varArray.filter(callbackFunc);
 var varBoolean  = varArray.every(callbackFunc);
 var varBoolean  = varArray.some(callbackFunc);
 var newValue    = varArray.reduce(callbackFunc); 
 var newValue    = varArray.reduceRight(callbackFunc); 

Methods forEach() and map()

The forEach() method applies a given rule (defined via the callback function) to all elements of the array. Thus, forEach() iterates through each element and calls the function for each of these elements. The forEach() method does not return anything; its return value is "undefined".

The callback function for forEach() method should accept three arguments, where the last two arguments are optional. These three arguments represent the value of the array element (the current element while iterating), the index of the current element, and the array itself.

Let us go through an example that shows the usage of the forEach() method. The example uses two callback functions, where one of the functions uses all the three arguments that can be used by the forEach() method.

The first callback function is give_me_total() and the forEach() method passes each element of the array ("a") to this function. This function adds these values and stores them in a global variable, "total". Once forEach() returns, the value of "total" becomes equal to sum of all the array elements.

The second callback shows the usage of all three arguments. We call forEach() with the callback function, multiply_by_two(). Here, we define all three arguments of value, index, and the array. With this callback, once forEach() is done iterating over all the elements of "a", these elements are all multiplied by two.

Here is the example (we print the output as code-comment):

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // First argument is the value of array element.
 function give_me_total(passed_val) {total += passed_val;}

 // Three arguments: array value, array index, and array itself.
 function multiply_by_two(passed_val, passed_index, passed_array) {
     passed_array[passed_index] = 2 * passed_val;
 }

 // Define an array.
 var a = [25, 50, 75, 100];
 var total = 0;

 a.forEach(give_me_total);
 elem.innerHTML += total;  // total equals 250

 a.forEach(multiply_by_two);
 elem.innerHTML += a;      // a equals [50, 100, 150, 200] 
 </script>
 </html>

Method map() behaves similar to forEach(). Like forEach(), the callback function for map() can also have three arguments. Similar to forEach(), map() does not alter the original array. However, map() differs from forEach() in two ways: (1) map() returns a new array and (2) the callback function for map() should have a return value.

Here is an example that illustrates usage of map() method.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Callback function.
 function add_another_100(passed_val) {return (passed_val + 100);}

 // Define an array.
 var a = [25, 50, 75, 100];

 var b = a.map(add_another_100);
 elem.innerHTML += a;    // a equals [25, 50, 75, 100] 
 elem.innerHTML += b;    // b equals [125, 150, 175, 200] 

 </script>
 </html>

Methods filter(), every(), and some()

Like the case of forEach() method, the callback functions for filter(), every(), and some() can also have three arguments: index, value, and the array. However, these callback functions should return a Boolean value (either true or false). These three methods either verify all the elements against a common criteria or filter all the elements against a common criteria.

All of these three methods leave the original array intact.

Method every() iterates through all elements and only when all the elements meet a specified criterion (defined via the callback function), it returns true, else it returns false.

Method some() is less restrictive -- it checks all the elements against the specified criterion and the moment it finds an element that meets the criterion, it returns true. Else, it iterates through all the elements and failing to find an element that meets the criterion, it returns false.

Method filter() iterates through all elements and creates (and returns) a new array that holds all the elements of the original array that meet the specified criterion.

We provide a simple example that contains these three methods. This example uses a callback function, "is_odd()", to verify if a given array element is an odd number.

 <!doctype html>
 <html>
 <script type="text/javascript"> 

 // Callback function.
 function is_odd(passed_val) {return (passed_val % 2);}

 // Define a simple array.
 var a = [25, 50, 75, 100];

 var b = a.filter(is_odd); // b equals [25, 75]
 var x = a.every(is_odd);  // x equals false 
 x = a.some(is_odd);       // x equals true

 </script>
 </html>

Methods reduce() and reduceRight()

Methods, reduce() and reduceRight(), accept a callback function that applies a given logic to each subsequent element of the array (as these methods iterate) and then ultimately returns the final value. Thus, these methods take an array and return a single value and hence, the name "reduce".

Both of these methods leave the original array intact.

Method reduce() uses values returned for each element to modify a cumulative value, for example summation of elements. Once it is done with all elements, it returns the final cumulative value, for example the sum of all elements. The callback to reduce() can take up-to four arguments: the previous value (the reduced value so far), the current value, the current index, and the array itself.

Where as, reduce() iterates array elements from the first element and progresses towards the last element, the reduceRight() method starts at the last element and proceeds towards the first element.

We use an example to show usage of these two methods. This example uses a callback function, "give_me_total()", to return the sum of the passed arguments. Note that both of these methods can also accept an initial value besides a callback function and we pass that value as 0.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Callback function.
 function give_me_total (passed_val1, passed_val2) {
     elem.innerHTML += "arg1: " + passed_val1 + ", arg2: " + passed_val2 + "<br>";
     return (passed_val1 + passed_val2);
 }

 // Define an array.
 var a = [25, 50, 75, 100];

 elem.innerHTML += "With reduce(): <br>";
 var total = a.reduce(give_me_total, 0);   // total equals 250

 elem.innerHTML += "<br>With reduceRight(): <br>";
 total = a.reduceRight(give_me_total, 0);  // total equals 250

 </script>
 </html>

When we run this example, we see the following output. The output shows that at each call, the first argument is the previous value (or the reduced value so far) -- the first argument starts with 0, then becomes (0 + 25), then becomes ( 0 + 25 + 50), and so on. For the reduceRight(), we see the same behavior, except that the progression happens from right to left.

 With reduce(): 
 arg1: 0, arg2: 25
 arg1: 25, arg2: 50
 arg1: 75, arg2: 75
 arg1: 150, arg2: 100

 With reduceRight(): 
 arg1: 0, arg2: 100
 arg1: 100, arg2: 75
 arg1: 175, arg2: 50
 arg1: 225, arg2: 25




comments powered by Disqus