[javascript] How might I find the largest number contained in a JavaScript 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?

This question is related to javascript algorithm arrays max

The answer is


Use:

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

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

console.log(largest);

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

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

_x000D_
_x000D_
const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];_x000D_
const maxNumber = Math.max(...inputArray);_x000D_
console.log(maxNumber);
_x000D_
_x000D_
_x000D_


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.


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

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

let array = [267, 306, 108]
let longest = Math.max(...array);

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

One for/of loop solution:

_x000D_
_x000D_
const numbers = [2, 4, 6, 8, 80, 56, 10];_x000D_
_x000D_
_x000D_
const findMax = (...numbers) => {_x000D_
  let currentMax = numbers[0]; // 2_x000D_
_x000D_
  for (const number of numbers) {_x000D_
    if (number > currentMax) {_x000D_
      console.log(number, currentMax);_x000D_
      currentMax = number;_x000D_
    }_x000D_
  }_x000D_
  console.log('Largest ', currentMax);_x000D_
  return currentMax;_x000D_
};_x000D_
_x000D_
findMax(...numbers);
_x000D_
_x000D_
_x000D_


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

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;

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

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

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

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

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

Simplest Way:

var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[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
}

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.


Using - Array.prototype.reduce() is cool!

[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)

where acc = accumulator and val = current value;

_x000D_
_x000D_
var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val);_x000D_
_x000D_
console.log(a);
_x000D_
_x000D_
_x000D_


Simple one liner

[].sort().pop()

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)

Run this:

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

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


You can also use forEach:

_x000D_
_x000D_
var maximum = Number.MIN_SAFE_INTEGER;_x000D_
_x000D_
var array = [-3, -2, 217, 9, -8, 46];_x000D_
array.forEach(function(value){_x000D_
  if(value > maximum) {_x000D_
    maximum = value;_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(maximum); // 217
_x000D_
_x000D_
_x000D_


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

A recursive approach on how to do it using ternary operators

_x000D_
_x000D_
const findMax = (arr, max, i) => arr.length === i ? max :_x000D_
  findMax(arr, arr[i] > max ? arr[i] : max, ++i)_x000D_
_x000D_
const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
const max = findMax(arr, arr[0], 0)_x000D_
console.log(max);
_x000D_
_x000D_
_x000D_


Find Max and Min value using Bubble Sort

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


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


The easiest syntax, with the new spread operator:

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

Source : Mozilla MDN


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


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to algorithm

How can I tell if an algorithm is efficient? Find the smallest positive integer that does not occur in a given sequence Efficiently getting all divisors of a given number Peak signal detection in realtime timeseries data What is the optimal algorithm for the game 2048? How can I sort a std::map first by value, then by key? Finding square root without using sqrt function? Fastest way to flatten / un-flatten nested JSON objects Mergesort with Python Find common substring between two strings

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to max

Min and max value of input in angular4 application numpy max vs amax vs maximum mongodb how to get max value from collections Python find min max and average of a list (array) Max length UITextField How to find the highest value of a column in a data frame in R? MAX function in where clause mysql Check if all values in list are greater than a certain number How do I get the max and min values from a set of numbers entered? SQL: Group by minimum value in one field while selecting distinct rows