Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding largest integer in an array in JavaScript [duplicate]

Tags:

javascript

Possible Duplicate:
How might I find the largest number contained in a JavaScript array?

I am having trouble getting this code to work. I have been at it for a while trying to figure it out. When I look at the console it just displays 0. What did I do wrong?

Here is my code:

var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;

for (i=0; i<=largest;i++){
    if (array>largest) {
        var largest=array[i];
    }
}

console.log(largest);
like image 285
George Agusta Avatar asked Dec 10 '12 02:12

George Agusta


2 Answers

var arr = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = arr[0];

for (var i = 0; i < arr.length; i++) {
    if (largest < arr[i] ) {
        largest = arr[i];
    }
}
console.log(largest);
  • You need to define i or else it become a global variable.
  • Don't redefine largest in the loop.
  • Since you're looping through the array, use i < array.length instead of i <= largest.
  • Since you're comparing each of the items in the array to largest, use if(largest < array[i]) instead of if(array > largest)
  • You should set largest equal to the first element in the array because what if all the numbers are negative?
  • array is a bad variable name because it's too similar to Array (the array constructor). Try arr instead.

One liner:

var largest = Math.max.apply(0, array);

More info here: Javascript max() function for 3 numbers

like image 161
Larry Battle Avatar answered Sep 21 '22 18:09

Larry Battle


The code below is fixed and should work. The problem was that in this line if (array>largest) { You were not providing the index of the array. By changing the code to this if (array[i]>largest) { it works. Notice that I added the [i] to the end of array in the if statement.

var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;

for (i=0; i<=largest;i++){
    if (array[i]>largest) {
        var largest=array[i];
    }
}




console.log(largest);
like image 38
Yamaha32088 Avatar answered Sep 19 '22 18:09

Yamaha32088