jQuery get biggest number from list

16,366

Solution 1

If you have them in an array, you can do this:

var numbers_array = [1415, 2343, 11];

numbers_array.push( 432 ); // now the array is [1415, 2343, 11, 432]

var biggest = Math.max.apply( null, numbers_array );

Solution 2

Math.max(one, two, three)

Solution 3

That will work 100%

var max = Math.max.apply(Math, "your array");

Solution 4

If your values are in an array, try reduce :

var biggestValue = myArray.reduce( function(a,b){ return a > b ? a : b ; } );

Solution 5

Put them in an array, sort them, and take the last of the sorted values:

[one, two, three].sort(function (a, b) {
  return a > b ? 1 : (a < b ? -1 : 0);
}).slice(-1);
Share:
16,366
James
Author by

James

Updated on July 21, 2022

Comments

  • James
    James almost 2 years
    var one = 1415;
    var two = 2343;
    var three = 11;
    

    How to get the biggest number from these variables?

  • shabunc
    shabunc over 13 years
    Todd, actually, there's no any guarantee, that array will be sorted numerically. You should sort this way - [n1,n2,n3].sort(function(a,b){return a>b?1:a<b?-1:0})
  • shabunc
    shabunc over 13 years
    @WorkingHard, you can use either Math.max.apply(null,[3,2,1]) or sort array (by desc) and take the first element - [1,4,3,2].sort(function(a,b){return a<b?1:a>b?-1:0})[0]
  • RightSaidFred
    RightSaidFred over 13 years
    @WorkingHard - You use .push() to add items to the top of an array. I'll give an example in my answer.
  • Todd Yandell
    Todd Yandell over 13 years
    Interesting, I didn’t realize that. It sorts each item based on its string representation, so 30 comes before 4.
  • Cristian Sanchez
    Cristian Sanchez over 13 years
    Why wouldn't you just call Math.max regularly in that case?
  • Admin
    Admin over 12 years
    It looks like IE8 (at least, possibly further down) doesn't support Array.reduce. Either use a different method outlined here or you can add compatibility code from Mozilla Reference Docs