0

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

2 Answers 2

1

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

function getMaxOfArray(numArray) {
    return Math.max.apply(null, numArray);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.