222

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?

1
  • 27
    Math.max(...[267, 306, 108]); Commented Nov 14, 2016 at 16:29

32 Answers 32

324

Resig to the rescue:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Warning: since the maximum number of arguments is as low as 65535 on some VMs, use a for loop if you're not certain the array is that small.

Sign up to request clarification or add additional context in comments.

18 Comments

Ah, but now it has the SO Sticker of Quality affixed to it in an only slightly-crooked fashion!
FWIW, if performance is a factor in your solution, I would test that compared to your own easily-coded function to make sure it performs well. We tend to assume that the native implementation will be faster; in fact, the cost of the apply call can wash that out very easily.
What if my array length is bigger than parameter count limit ?
@CrescentFresh according to this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… it is hardcoded to 65535. According to this: code.google.com/p/v8/issues/detail?id=172 and by knowledge that arguments are pushed onto stack we know that it's not unlimited
Also, this method is not robust. It fails if your array is larger than the the mamximum stack size resulting in RangeError: Maximum call stack size exceeded.
|
208

You can use the apply function, to call Math.max:

var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306

How does it work?

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.

3 Comments

Whoa you put on your answers with a lot of effort :D
That's great. But what if my array length exceeds parameter size limit(of function)? What then ?
I like this answer better than the others because it explains what everything does and why. +1
66

The easiest syntax, with the new spread operator:

var arr = [1, 2, 3];
var max = Math.max(...arr);

Source : Mozilla MDN

3 Comments

However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@Green FWIW, the parameter count limit is 65536 (at least on Chrome) ([source(bugs.webkit.org/show_bug.cgi?id=80797)]). So if your array has more than 65536 elements, this answer won't work.
65536 ought to be enough for anybody
49

I'm not a JavaScript 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:

  • reduce took 4.0392 ms to run
  • Math.max.apply took 3.3742 ms to run
  • sorting and getting the 0th value took 67.4724 ms to run
  • Math.max within reduce() took 6.5804 ms to run
  • custom findmax function took 1.6102 ms to run

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)

2 Comments

For me, this is the best answer for this question.
I've made jsperf tests for the above
38

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;
}

Benchmark results

1 Comment

FWIW, comes out to 84% now on Chrome 31.
33

You could sort the array in descending order and get the first item:

[267, 306, 108].sort(function(a,b){return b-a;})[0]

8 Comments

I would assume you could also just sort and get the last item...?
@Shog9: Yes, but you would need to specify the comparison function on your own: sort(function(a,b){return b-a;})
Ah. I was thinking more like: [...].sort().pop()
"finding the number takes order-n, sorting takes between order(n log n) to order(n squared), dependig on the sort algorithm used" - webmasterworld.com/forum91/382.htm
Also keep in mind that this sorts the array, which may or may not be a desired side effect. The apply solution is better performing and has no side effects.
|
31

Use:

var arr = [1, 2, 3, 4];

var largest = arr.reduce(function(x,y) {
    return (x > y) ? x : y;
});

console.log(largest);

2 Comments

Had I see this answer first (currently at the bottom of the list) I would have saved two hours.
The Math.max approach is probably the most standard, but I was getting a stack overflow when the array was too large (500K). This answer is fast and efficient and is the one I ended up using myself, so I'm upvoting this one.
9

Use Array.reduce:

[0,1,2,3,4].reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});

3 Comments

Initial value should be set to -Infinity.
@Jack, why is this needed? even with an array of all negative numbers, I get a valid result.
It's the edge case whereby the array is empty.
7

To find the largest number in an array you just need to use Math.max(...arrayName);. It works like this:

let myArr = [1, 2, 3, 4, 5, 6];
console.log(Math.max(...myArr));

To learn more about Math.max: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

Comments

5

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);

1 Comment

However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
5

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;
}

1 Comment

findmax() gives the wrong result if there are only negative numbers in the array; findmin() gives the wrong result for an empty array.
5

Simple one liner

[].sort().pop()

Comments

5

Almost all of the answers use Math.max.apply() which is nice and dandy, but it has limitations.

Function arguments are placed onto the stack which has a downside - a limit. So if your array is bigger than the 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.

The 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.

2 Comments

This is not fair. I want the answer right here, on SO, not another link to another third-party resource. Especially when it's combined with "everything here is bad, but go, look, it's so great on my blog..."
@SergeyOrshanskiy a link to a third party works very well in case it's updated with new insigths and solutions. Also no need to feel offended. People just want to solve your problems too. I wanted to solve it too, so I wrote about it on my blog
3

Yes, of course there exists Math.max.apply(null,[23,45,67,-45]) and the result is to return 67.

Comments

1

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

Comments

1

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() );

3 Comments

Terribly inefficient.
@FrankSchmitt, thank you, I agree. Original answer was not a good solution. Sort by default does not sort numbers, it treats elements as strings. Edited my answer to have the right sort.
That was not my point. Sorting an Array to find the maximum is per se terribly inefficient, since it takes at least N log N operations, whereas finding the maximum can be done in N operations.
1

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

Comments

1

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);

Comments

1

A recursive approach on how to do it using ternary operators

const findMax = (arr, max, i) => arr.length === i ? max :
  findMax(arr, arr[i] > max ? arr[i] : max, ++i)

const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const max = findMax(arr, arr[0], 0)
console.log(max);

Comments

1

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);

Comments

1

I just started with JavaScript, but I think this method would be good:

var array = [34, 23, 57, 983, 198];
var score = 0;

for(var i = 0; i = array.length; i++) {
  if(array[ i ] > score) {
    score = array[i];
  }
}

1 Comment

This will have trouble if array contains only negative numbers.
1

var nums = [1,4,5,3,1,4,7,8,6,2,1,4];
nums.sort();
nums.reverse();
alert(nums[0]);

Simplest Way:

var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);

Comments

0

Run this:

Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

And now try [3,10,2].max() returns 10

Comments

0

Find Max and Min value using Bubble Sort

    var arr = [267, 306, 108];

    for(i=0, k=0; i<arr.length; i++) {
      for(j=0; j<i; j++) {
        if(arr[i]>arr[j]) {
          k = arr[i];
          arr[i] = arr[j];
          arr[j] = k;
        }
      }
    }
    console.log('largest Number: '+ arr[0]);
    console.log('Smallest Number: '+ arr[arr.length-1]);

1 Comment

(1) Javascript arrays already have a O(n log n) sort function. (2) Bubble sort is O(n^2). (3) Finding the min and max is O(n).
0

Try this

function largestNum(arr) {
  var currentLongest = arr[0]

  for (var i=0; i< arr.length; i++){
    if (arr[i] > currentLongest){
      currentLongest = arr[i]
    }
  }

  return currentLongest
}

1 Comment

Is this answer substantially different from many of the others on this page?
0

As per @Quasimondo's comment, which seems to have been largely missed, the below seems to have the best performance as shown here: https://jsperf.com/finding-maximum-element-in-an-array. Note that while for the array in the question, performance may not have a significant effect, for large arrays performance becomes more important, and again as noted using Math.max() doesn't even work if the array length is more than 65535. See also this answer.

function largestNum(arr) {
    var d = data;
    var m = d[d.length - 1];
    for (var i = d.length - 1; --i > -1;) {
      if (d[i] > m) m = d[i];
    }
    return m;
}

Comments

0

One for/of loop solution:

const numbers = [2, 4, 6, 8, 80, 56, 10];


const findMax = (...numbers) => {
  let currentMax = numbers[0]; // 2

  for (const number of numbers) {
    if (number > currentMax) {
      console.log(number, currentMax);
      currentMax = number;
    }
  }
  console.log('Largest ', currentMax);
  return currentMax;
};

findMax(...numbers);

Comments

0

Find the largest number in a multidimensional array

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;

4 Comments

It is always advisable to add some elaborate explanation to your code, especially if there are already multiple other answers. Why is this one different/better?
@Bowdzone ,thanks for the comment. this way is very basic what makes it simple to understand with a little knowledge of just few methods.
This doesn't return the largest number, it returns an array of the largest number of each array in the multidimensional array. You would need to add e.g. var tmax = Math.max.apply(Math, max), or better yet, use a closure of a loop function e.g. in stackoverflow.com/a/54980012/7438857. With this modification, it is better answered to a separate question, how do you "find the largest number in a multidimensional array", or at stackoverflow.com/questions/32616910/…. WIP: jsfiddle.net/jamesray/3cLu9for/8.
stackoverflow.com/a/32617019/7438857 is a better answer to the right question, while this answer doesn't answer the above question, it returns the largest number in each array within a multidimensional array.
0

My solution to return largest numbers in arrays.

const largestOfFour = arr => {
    let arr2 = [];
    arr.map(e => {
        let numStart = -Infinity;
        e.forEach(num => {
            if (num > numStart) {
                numStart = num;

            }
        })
        arr2.push(numStart);
    })
    return arr2;
}

Comments

0

Should be quite simple:

var countArray = [1,2,3,4,5,1,3,51,35,1,357,2,34,1,3,5,6];

var highestCount = 0;
for(var i=0; i<=countArray.length; i++){    
    if(countArray[i]>=highestCount){
    highestCount = countArray[i]
  }
}

console.log("Highest Count is " + highestCount);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.