Get the minimum and maximum of an Array - Node.js Array

Node.js examples for Array:Array Value

Description

Get the minimum and maximum of an Array

Demo Code

/*//from   ww  w .  j  av  a2s . c o m
 * Get the minimum and maximum of an Array, if the array is to
 * big it has to do it recursively because funcitons like Math.min don't
 * take an infinite amount of arguments and that could have been inteligently
 * solved by taking a array instead. But we have to live with is and just accept
 * that somethings aren't perfect.
 */
if(Array.prototype.min === undefined){

  Array.prototype.min = function() {
    var increment = 50000;
    if(this.length > increment){
      var reduced_array = [];
      for(var i=0;i<this.length;i+=increment) {
  reduced_array.push(Math.min.apply(Math, this.slice(i,i+increment-1)));
      }
    }else {
      return Math.min.apply(Math, this);
    }
    return reduced_array.min();

  };

}
if(Array.prototype.max === undefined) {

  Array.prototype.max = function(array) {
    var increment = 50000;
    if(this.length > increment){
      var reduced_array = [];
      for(var i=0;i<this.length;i+=increment) {
  reduced_array.push(Math.max.apply(Math, this.slice(i,i+increment-1)));
      }
    }else {
      return Math.max.apply(Math, this);
    }
    return reduced_array.max();
  };

}

Related Tutorials