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?
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:
You could also extend
Array
to have this function and make it part of every array.You can use the apply function, to call Math.max:
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:
The apply function will execute:
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.
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:
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/):
I have written about this question on my blog here.
Find the largest number in a multidimensional array
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 thanMath.max.apply()
:Benchmark results