221

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]);
    – Jacksonkr
    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.

18
  • 16
    Ah, but now it has the SO Sticker of Quality affixed to it in an only slightly-crooked fashion!
    – Shog9
    Sep 4, 2009 at 14:26
  • 2
    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. Sep 4, 2009 at 14:36
  • 2
    What if my array length is bigger than parameter count limit ? Oct 3, 2013 at 14:20
  • 3
    @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 Oct 3, 2013 at 17:48
  • 9
    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. Jul 1, 2015 at 11:49
209

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
  • 2
    Whoa you put on your answers with a lot of effort :D Sep 26, 2012 at 18:09
  • 1
    That's great. But what if my array length exceeds parameter size limit(of function)? What then ? Oct 3, 2013 at 14:13
  • 1
    I like this answer better than the others because it explains what everything does and why. +1
    – Marvin
    Aug 7, 2018 at 20:08
66

The easiest syntax, with the new spread operator:

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

Source : Mozilla MDN

3
47

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
  • 8
    For me, this is the best answer for this question.
    – rzelek
    Jul 21, 2015 at 16:35
  • 1
    I've made jsperf tests for the above
    – vsync
    Jul 9, 2018 at 16:16
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
  • 4
    FWIW, comes out to 84% now on Chrome 31.
    – Ilan Biala
    Dec 15, 2013 at 1:33
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
  • 5
    I would assume you could also just sort and get the last item...?
    – Shog9
    Sep 4, 2009 at 14:24
  • @Shog9: Yes, but you would need to specify the comparison function on your own: sort(function(a,b){return b-a;})
    – Gumbo
    Sep 4, 2009 at 15:05
  • 9
    Ah. I was thinking more like: [...].sort().pop()
    – Shog9
    Sep 4, 2009 at 15:33
  • 4
    "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 Oct 15, 2011 at 2:34
  • 3
    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.
    – Caleb
    Jan 16, 2013 at 22:14
31

Use:

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

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

console.log(largest);
2
  • Had I see this answer first (currently at the bottom of the list) I would have saved two hours.
    – user139301
    May 16, 2015 at 19:45
  • 1
    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.
    – Jason
    Mar 12, 2018 at 14:25
9

Use Array.reduce:

[0,1,2,3,4].reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});
3
  • Initial value should be set to -Infinity.
    – Ja͢ck
    Sep 25, 2014 at 22:51
  • @Jack, why is this needed? even with an array of all negative numbers, I get a valid result.
    – CodeToad
    Sep 28, 2014 at 8:06
  • 1
    It's the edge case whereby the array is empty.
    – Ja͢ck
    Sep 28, 2014 at 10:13
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

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
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
  • findmax() gives the wrong result if there are only negative numbers in the array; findmin() gives the wrong result for an empty array.
    – Ja͢ck
    Sep 25, 2014 at 22:52
5

Simple one liner

[].sort().pop()
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
  • 2
    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..." Oct 15, 2013 at 0:19
  • @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 Oct 15, 2013 at 8:21
3

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

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
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
  • 1
    Terribly inefficient. Jul 26, 2014 at 18:59
  • @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.
    – Izz
    Sep 24, 2014 at 6:27
  • 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. Sep 24, 2014 at 6:42
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

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

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

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);
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
  • This will have trouble if array contains only negative numbers.
    – Teepeemm
    Dec 27, 2018 at 13:11
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]);
0

Run this:

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

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

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
  • 1
    (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).
    – Teepeemm
    Dec 27, 2018 at 13:18
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
  • 1
    Is this answer substantially different from many of the others on this page?
    – Teepeemm
    Dec 27, 2018 at 13:16
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;
}
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);

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
  • 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
    Aug 11, 2015 at 8:09
  • @Bowdzone ,thanks for the comment. this way is very basic what makes it simple to understand with a little knowledge of just few methods. Aug 12, 2015 at 14:09
  • 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.
    – James Ray
    Mar 4, 2019 at 11:23
  • 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.
    – James Ray
    Mar 4, 2019 at 23:38
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;
}
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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.