Sunday, July 12, 2015

Calling JavaScript inner array methods

JavaScript array methods may be placed inside an outer array method. When the outer method is run, the inner method is run against the current array element. In this post, the array that will be used is still the objects containing computer units issued to persons. The objective is to determine the percentage of an individual free HD space against the total HD free space:


The standard approach using a for() loops would be as follows:

<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var totalFree = 0;
 
 for(var i =0; i < units.length; i++){
  totalFree += units[i].GBHDFree;
 }
 
 var freePercent = [];
 
 for(var i =0; i < units.length; i++){
  freePercent.push((units[i].GBHDFree/totalFree) * 100);
 }
 
 console.log(freePercent);
 </script>

An alternative approach is to use the array map() method to create a parallel array to the units array. The map() method calls a function that goes through each object element and determines the elements free HD space.


The function then calls a combine units array map() and reduce() methods. The map() creates a parallel array of free HD space for each units object element. The reduce() computes the total of each element (Free HD space) in the parallel array.


The combine map() and reduce() are the inner methods called by the function in the outer map() method. The code snipper is listed below:
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 var getPercentageFree = function(unit){
  var free = unit.GBHDFree;
  var totalFree = units.map(function(unit){return unit.GBHDFree}).reduce(function(start, current){
   return start + current;
  }, 0);
  return (free / totalFree) * 100;
 }
 
 console.log(units.map(getPercentageFree));
 
 </script>

The full code is available at:
https://github.com/jundolor/JavaScript/blob/master/callinginnerarraymethods.html

No comments:

Post a Comment