Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max / min of large array in JS

Tags:

javascript

I need to calculate min/max of large array. I know about Math.max.apply(), but on large arrays it fails with Stack overflow exception. Any simple solutions?

like image 312
Alexey Timanovsky Avatar asked Jun 05 '13 18:06

Alexey Timanovsky


3 Answers

  1. Sort the array by using sort() method it sorts array by using quicksort algorithm

  2. Since array is sorted in ascending order then the last element is the max

    var arr = [1,4,6,4, ...];
    arr.sort((a, b) => a - b);
    var max = arr[arr.length - 1];
    
like image 60
Nikola Mitev Avatar answered Oct 17 '22 15:10

Nikola Mitev


Array.prototype.min = function() {
    var r = this[0];
    this.forEach(function(v,i,a){if (v<r) r=v;});
    return r;
};

From JavaScript: min & max Array values? where other solutions from this problem are discussed

FYI: I just googled "max min large array" and found this as the first result...

like image 21
Antoine Avatar answered Oct 17 '22 13:10

Antoine


Why not just loop through the entire array?

var max = Number.MIN_VALUE, min = Number.MAX_VALUE;
for (var i = 0, len=list.length; i < len; i++) {
   if (list[i] > max) max = list[i];
   if (list[i] < min) min = list[i];
}

Edit:

For max:

if (typeof Array.prototype.GetMax === "undefined") {
    Array.prototype.GetMax = function() {
        var max = Number.MAX_VALUE;
        for (var i = 0, len=this.length; i < len; i++) {
           if (this[i] > max) max = this[i];
        }
        return max;
    }
}

For min:

if (typeof Array.prototype.GetMin === "undefined") {
    Array.prototype.GetMin = function() {
        var min = Number.MIN_VALUE;
        for (var i = 0, len=this.length; i < len; i++) {
           if (this[i] < min) min = this[i];
        }
        return min;
    }
}

For both:

if (typeof Array.prototype.GetMaxMin === "undefined") {
    Array.prototype.GetMaxMin = function() {
        var max = Number.MIN_VALUE, min = Number.MAX_VALUE;
        for (var i = 0, len=this.length; i < len; i++) {
            if (this[i] > max) max = this[i];
            if (this[i] < min) min = this[i];
        }
        return { Max: max, Min: min};
    }
}
like image 31
David Sherret Avatar answered Oct 17 '22 13:10

David Sherret