I have a simple JavaScript Array object containing a few numbers.
[267, 306, 108]
Is there a function that would find the largest number in this array?
I have a simple JavaScript Array object containing a few numbers.
[267, 306, 108]
Is there a function that would find the largest number in this array?
Array.max = function( array ){ return Math.max.apply( Math, array ); };
You can use the apply function, to call Math.max:
var array = [267, 306, 108]; var largest = Math.max.apply(Math, array); // 306
How it works?
The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)
So if we call:
Math.min.apply(Math, [1,2,3,4]);
The apply function will execute:
Math.min(1,2,3,4);
Note that the first parameter, the context, is not important for these functions since they are static, they will work regardless of what is passed as the context.
I've found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for
loop, performing ~30% better than Math.max.apply()
:
function mymax(a) { var m = -Infinity, i = 0, n = a.length; for (; i != n; ++i) { if (a[i] > m) { m = a[i]; } } return m; }
I'm no JS expert, but I wanted to see how these methods stack up, so this was good practice for me. I don't know if this is technically the right way to performance test these, but I just ran them one right after another, as you can see in my code.
Sorting and getting the 0th value is by far the worst method (and it modifies the order of your array, which may not be desirable). For the others, the difference is negligible unless you're talking millions of indices.
Average results of five runs with a 100,000-index array of random numbers:
var performance = window.performance function findmax(array) { var max = 0, a = array.length, counter for (counter=0;counter<a;counter++) { if (array[counter] > max) { max = array[counter] } } return max } function findBiggestNumber(num) { var counts = [] var i for (i = 0; i < num; i++) { counts.push(Math.random()) } var a, b a = performance.now() var biggest = counts.reduce(function(highest, count){ return highest > count ? highest : count }, 0) b = performance.now() console.log('reduce took ' + (b - a) + ' ms to run') a = performance.now() var biggest2 = Math.max.apply(Math, counts) b = performance.now() console.log('Math.max.apply took ' + (b - a) + ' ms to run') a = performance.now() var biggest3 = counts.sort(function(a,b){return b-a;})[0] b = performance.now() console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run') a = performance.now() var biggest4 = counts.reduce(function(highest, count){ return Math.max(highest,count) }, 0) b = performance.now() console.log('Math.max within reduce() took ' + (b - a) + ' ms to run') a = performance.now() var biggest5 = findmax(counts) b = performance.now() console.log('custom findmax function took ' + (b - a) + ' ms to run') console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5) } findBiggestNumber(1E5)
The easiest syntax, with the new spread operator:
var arr = [1, 2, 3]; var max = Math.max(...arr);
Source : Mozilla MDN
You could sort the array in descending order and get the first item:
[267, 306, 108].sort(function(a,b){return b-a;})[0]
How about this:
var arr = [1,2,3,4]; var largest = arr.reduce(function(x,y){ return (x > y) ? x : y; }); console.log(largest);
how about using Array.reduce ?
[0,1,2,3,4].reduce(function(previousValue, currentValue){ return Math.max(previousValue,currentValue); });
Finding max and min value the easy and manual way. This code is much faster than Math.max.apply
; I have tried up to 1000k numbers in array.
function findmax(array) { var max = 0; var a = array.length; for (counter=0;counter<a;counter++) { if (array[counter] > max) { max = array[counter]; } } return max; } function findmin(array) { var min = array[0]; var a = array.length; for (counter=0;counter<a;counter++) { if (array[counter] < min) { min = array[counter]; } } return min; }
Almost all of the answers use Math.max.apply()
which is nice and dandy but has limitations.
Function arguments are placed onto stack which has a downside - a limit. So if your array is bigger than limit it will fail with RangeError: Maximum call stack size exceeded.
To find a call stack size I used this code:
var ar = []; for (var i = 1; i < 100*99999; i++) { ar.push(1); try { var max = Math.max.apply(Math, ar); } catch(e) { console.log('Limit reached: '+i+' error is: '+e); break; } }
It proved to be biggest on FireFox on my machine - 591519. This means that if you array contains more than 591519 items, Math.max.apply()
will result in RangeError.
Best solution for this problem is iterative way(credit: https://developer.mozilla.org/):
max = -Infinity, min = +Infinity; for (var i = 0; i < numbers.length; i++) { if (numbers[i] > max) max = numbers[i]; if (numbers[i] < min) min = numbers[i]; }
I have written about this question on my blog here.
Yes of course exist: Math.max.apply(null,[23,45,67,-45])
and the result return 67
;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18]; const maxNumber = Math.max(...inputArray); console.log(maxNumber);
Don't forget that the wrap can be done with Function.prototype.bind
, giving you an "all-native" function.
var aMax = Math.max.apply.bind(Math.max, Math); aMax([1, 2, 3, 4, 5]); // 5
You could also extend Array
to have this function and make it part of every array.
Array.prototype.max = function(){return Math.max.apply( Math, this )}; myArray = [1,2,3]; console.log( myArray.max() );
var max = []; for(var i=0; arr.length>i; i++ ){ var arra = arr[i]; var largest = Math.max.apply(Math, arra); max.push(largest); } return max;
You can also use forEach:
var maximum = Number.MIN_SAFE_INTEGER; var array = [-3, -2, 217, 9, -8, 46]; array.forEach(function(value){ if(value > maximum) { maximum = value; } }); console.log(maximum); // 217
Using - Array.prototype.reduce()
is cool!
[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)
where acc = accumulator and val = current value;
var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val); console.log(a);
You can try this,
var arr = [267,306,108]; var largestNum = 0; for(i=0;i<arr.length;i++) { if(arr[i]>largest){ var largest = arr[i]; } } console.log(largest);
I just started with JS but I think this method would be good:
var array = [34, 23, 57, 983, 198];<br> var score = 0; for(var i = 0; i = array.length; i++) { if(array[ i ] > score) { score = array[i]; } }
Run this:
Array.prototype.max = function(){ return Math.max.apply( Math, this ); };
And now try [3,10,2].max()
returns 10