sritno
sritno

Reputation: 217

javascript finding biggest number in array not working

i'm filling an array from the input fields and i need to find the biggest number in that array.

Using Math.max(myData) gives me NaN error and when i'm using the "if" statement,sometimes it works and sometimes it doesn't. Example: if i have 40 and 100 in array ,it gives me 40 as bigger number,but when i have 500 than it works fine.

if i want to make Math.max to work i need to make a new function that converts string into numbers,right?

my code,so you can see where is the mistake.

function Data() {

        var h = 0;
        var secnd = 1;  
         var najBr = 0;     
        for (var i = 0; i < valGrup2; i++) 
        {
            var first = 1;               
            myDataName[i] = document.getElementById('ime' + secnd).value;

            for (var j = 0; j < val2; j++) 
            { 
                myData[h] = document.getElementById("inputpolja" + first + secnd).value;
                if(myData[h]>najBr){
                najBr=myData[h];
                }
                myDataValue[h] = document.getElementById("inputpolja" + first + secnd).value;
                h++;
                first++;
            }
            secnd++;
        }

    //najBr=Math.max(myData);
console.log(najBr);

Upvotes: 0

Views: 61

Answers (2)

Scimonster
Scimonster

Reputation: 33409

Math.max takes multiple arguments, not an array of the numbers. You can use Function#apply() to have it treat the array as a list of arguments:

Math.max.apply(null /* the context */, myData)

Upvotes: 1

iMacTia
iMacTia

Reputation: 671

Math.max accepts only plain numbers, not an array. Use this:

function getMaxOfArray(numArray) {
    return Math.max.apply(null, numArray);
}

Upvotes: 1

Related Questions