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?

Shog9
  • 156,901
  • 35
  • 231
  • 235
dotty
  • 40,405
  • 66
  • 150
  • 195

32 Answers32

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.

Andy
  • 7,885
  • 5
  • 55
  • 61
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • Christ. 90 rep in 3 minutes for an answer that would have been faster to google. – Crescent Fresh Sep 04 '09 at 14:23
  • 16
    Ah, but now it has the **SO Sticker of Quality** affixed to it in an only slightly-crooked fashion! – Shog9 Sep 04 '09 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. – T.J. Crowder Sep 04 '09 at 14:36
  • By the way, this only works reliably with number values (not, say, string ones), whereas `sort` -based solution works with strings and objects. – kangax Sep 04 '09 at 20:07
  • 1
    @kangax: on the other hand, if you have a mix of numbers and string representations of numbers, the `sort()` -based method *may* not do what you expect. Try: `["7", "50", 300]`... – Shog9 Sep 04 '09 at 21:19
  • 2
    What if my array length is bigger than parameter count limit ? – lukas.pukenis Oct 03 '13 at 14:20
  • @lukas.pukenis: what is the parameter count limit? And is it part of the ECMAScript standard or a particular implementation (i.e. V8)? – Crescent Fresh Oct 03 '13 at 17:39
  • 3
    @CrescentFresh according to this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply it is hardcoded to 65535. According to this: https://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 – lukas.pukenis Oct 03 '13 at 17:48
  • @lukas.pukenis: nice references. Evidently the behavior is undefined. – Crescent Fresh Oct 04 '13 at 14:25
  • @CrescentFresh I was very interested in this topic so I posted my own answer and provided link to testing for a limit. Of course I may be wrong! But your method despite being elegant, fails with very big arrays. That's just a note :) – lukas.pukenis Oct 04 '13 at 14:27
  • 2
    Whilst this solution is elegant unfortunately it perfoms much worse than a simple loop with a comparison. Here's a test that compares the various alternatives: http://jsperf.com/finding-maximum-element-in-an-array – Quasimondo Dec 29 '13 at 11:30
  • @Quasimondo: yes the cost of `apply` is high as T.J. Crowder points out. – Crescent Fresh Jan 06 '14 at 03:55
  • 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.` – Mark Lundin Jul 01 '15 at 11:49
  • @MarkLundin: raised by [@lukas.pukenis](http://stackoverflow.com/a/19167520/45433) two year ago – Crescent Fresh Jul 03 '15 at 16:43
  • @CrescentFresh The answer can be updated for new `ECMAScript 6` spread operator. – Vahid Hallaji Nov 18 '15 at 16:06
  • There are some inconsistencies here if the array is empty. E.g. `Math.max([]) = 0` while `Math.max.apply(Math, []) = -Infinity` – Andreas Finne Jan 05 '16 at 13:53
  • @AndreasFinne: `Math.max([])` [isn't a thing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max). You pass arguments separately. You do not bundle them up into a single array argument. – Crescent Fresh Jan 22 '16 at 14:52
  • Note that you can also do this: `Math.max.apply(this, array)` – thdoan Feb 08 '17 at 17:14
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
66

The easiest syntax, with the new spread operator:

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

Source : Mozilla MDN

A.I
  • 1,438
  • 2
  • 16
  • 18
  • 2
    _However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements_ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max – Green Dec 08 '17 at 14:01
  • @Green FWIW, the parameter count limit is 65536 (at least on Chrome) ([source(https://bugs.webkit.org/show_bug.cgi?id=80797)]). So if your array has more than 65536 elements, this answer won't work. – mgthomas99 Apr 06 '18 at 09:43
  • 6
    *65536 ought to be enough for anybody* – vsync Jul 09 '18 at 15:34
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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
redOctober13
  • 3,662
  • 6
  • 34
  • 61
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

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
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]
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 5
    I would assume you could also just sort and get the last item...? – Shog9 Sep 04 '09 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 04 '09 at 15:05
  • 9
    Ah. I was thinking more like: `[...].sort().pop()` – Shog9 Sep 04 '09 at 15:33
  • @Shog9: Nice, didn’t think of that. – Gumbo Sep 04 '09 at 15:56
  • +1 this is very usefull in case you have more then one highest number into the array! ;) very nice Shog9 & Gumbo – Luca Filosofi Sep 25 '10 at 22:36
  • 4
    "finding the number takes order-n, sorting takes between order(n log n) to order(n squared), dependig on the sort algorithm used" - http://www.webmasterworld.com/forum91/382.htm – Marco Luglio Oct 15 '11 at 02: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 '13 at 22:14
  • @vsync what? [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) says it's in place. So does a quick check in the browser console. – Caleb Jul 09 '18 at 13:22
31

Use:

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

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

console.log(largest);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
brroshan
  • 1,640
  • 17
  • 19
  • Had I see this answer first (currently at the bottom of the list) I would have saved two hours. – user139301 May 16 '15 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 '18 at 14:25
9

Use Array.reduce:

[0,1,2,3,4].reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CodeToad
  • 4,656
  • 6
  • 41
  • 53
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lukas.pukenis
  • 13,057
  • 12
  • 47
  • 81
  • 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..." – Sergey Orshanskiy Oct 15 '13 at 00: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 – lukas.pukenis Oct 15 '13 at 08:21
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;
}
mgthomas99
  • 5,402
  • 3
  • 19
  • 21
Yaser Ranjha
  • 107
  • 2
  • 9
  • `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 '14 at 22:52
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);
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50
  • 2
    _However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements_ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max – Green Dec 08 '17 at 13:59
5

Simple one liner

[].sort().pop()
YasirAzgar
  • 1,385
  • 16
  • 15
3

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
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
Paul S.
  • 64,864
  • 9
  • 122
  • 138
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() );
dee-see
  • 23,668
  • 5
  • 58
  • 91
Izz
  • 59
  • 3
  • 1
    Terribly inefficient. – Frank Schmitt Jul 26 '14 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 '14 at 06: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. – Frank Schmitt Sep 24 '14 at 06: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
Benny Code
  • 51,456
  • 28
  • 233
  • 198
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);
arora
  • 869
  • 7
  • 12
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aasha joney
  • 508
  • 5
  • 23
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];
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jakub Karki
  • 73
  • 1
  • 2
  • 6
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);
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
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

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Liveindream
  • 159
  • 1
  • 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 '15 at 08: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. – Liveindream Aug 12 '15 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 https://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 https://stackoverflow.com/questions/32616910/find-largest-number-in-a-2d-array-in-javascript. WIP: https://jsfiddle.net/jamesray/3cLu9for/8/. – James Ray Mar 04 '19 at 11:23
  • https://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 04 '19 at 23:38
0

Run this:

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

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

RegarBoy
  • 3,228
  • 1
  • 23
  • 44
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]);
Manoj
  • 2,000
  • 2
  • 16
  • 21
  • 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 '18 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
}
Toufiq
  • 1,096
  • 12
  • 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;
}
James Ray
  • 424
  • 3
  • 15
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);
Mile Mijatović
  • 2,948
  • 2
  • 22
  • 41
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);
0

highest and smallest value using sort with arrow function

var highest=[267, 306, 108,700,490,678,355,399,500,800].sort((a,b)=>{return b-a;})[0]
console.log(highest)
var smallest=[267, 306, 108,700,490,678,355,399,500,800].sort((a,b)=>{return a-b;})[0]
console.log(smallest)
Balaji
  • 9,657
  • 5
  • 47
  • 47
-1
let array = [267, 306, 108]
let longest = Math.max(...array);
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Trilok Singh
  • 1,227
  • 12
  • 10