18

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);
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
George Agusta
  • 191
  • 1
  • 1
  • 4

6 Answers6

36
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

Community
  • 1
  • 1
Larry Battle
  • 8,662
  • 4
  • 40
  • 55
  • 1
    Unfortunately Math.max is out as an option for very large arrays. In the testing I'm doing right now, the max array length that Math.max can handle is 123679 elements. This probably changes on javascript platform, but it illustrates that Math.max is *almost* as fast as straight iteration, but isn't quite as fast and fails for very large arrays. – Geuis Dec 10 '12 at 03:30
  • @Geuis I didn't know that, but that seems more like a memory issue to me. It might because of the way `apply` is implemented. What platform are you testing on? Do you have a link to your test? – Larry Battle Dec 10 '12 at 03:33
  • Here's a jsperf I modified with additional test cases. http://jsperf.com/array-sorting-javascript-stack/2 Note that Math.max appears slightly faster in Firefox, but not significantly faster. Appears a good old loop and if test is fastest. I added checks for while negation, and to see if ternary comparisons might be faster. They aren't. – Geuis Dec 10 '12 at 03:57
  • This will give array out of bound error.for (var i = 0; i < arr.length; i++) { if (largest < arr[i] ) { largest = arr[i]; } } console.log(largest); – Aakash Singh May 19 '20 at 09:19
20

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);
Yamaha32088
  • 3,882
  • 8
  • 41
  • 93
  • Don't redeclare largest in the if statement. You've already declared the var in the opening under array. – Geuis Dec 10 '12 at 03:02
  • 4
    This shouldn't be the accepted answer since there are more efficient ways to do this. – Geuis Dec 10 '12 at 03:56
  • This fails when the first array item is `0` or `negative`. It also fails if the array starts with two `1`s or three `2`s or so on. – Gibin Ealias May 08 '19 at 19:21
  • 1
    I am sure @Yamaha32088 made a mistake in the for loop. It should be be i <= array.length instead of i < largest. The condition will only pass for the first round of loop. – camelCase Oct 15 '19 at 21:48
  • This is not the solution now sure why there is a tick mark on solution This will give array out of bound error. beacuse of (var i = 0; i < arr.length; i++) -> this will over run the limit of length. var array = [3 , 6, 2, 56, 32, 5, 89, 32]; let largest= 0; function largestFunction() { for (var i = 0; i < arr.length; i++) { if (largest < arr[i] ) { largest = arr[i]; } } return largest; } console.log(largestFunction); – Aakash Singh May 19 '20 at 09:25
17

Just one line :)

var array = [3 , 6, 2, 56, 32, 5, 89, 32],
    largest = array.sort((a,b)=>a-b).reverse()[0];

or even better

...
    largest = array.sort((a,b)=>a-b)[array.length - 1];

UPD, all code above is sucks when you add for example 9 in array my guess because by default numbers treated as strings in sort, there is better version

var array = [3 , 6, 2, 56, 32, 5, 89, 32, 9], largest;
array.sort(function(a, b) {
   largest = a > b ? a: b;
});

although in performance wise forEach loop suggested in comments are better http://jsperf.com/array-sorting-javascript-stack

UPD2, okay, code above has some bad parts in it, so will not work as expected. Another try:

array.sort(function(a, b) {
  return a - b;
});
largest = array[array.length - 1];
Sultan Aslam
  • 4,353
  • 1
  • 33
  • 40
dmi3y
  • 3,302
  • 2
  • 20
  • 32
  • Cool, but sorting is slower. – Larry Battle Dec 10 '12 at 03:02
  • @LarryBattle compare with what? here is jsperf http://jsperf.com/array-sorting-javascript-stack, the only drowback here is if you have null defined elements, but need to check though – dmi3y Dec 10 '12 at 03:10
  • This is a VERY inefficient method. js array sorts are rather slow. http://jsfiddle.net/ychWw/ In my simple testing, method1 completes in around 50ms, while your method takes 5 seconds. – Geuis Dec 10 '12 at 03:11
  • @Geuis, yea foreach cool) what about support? and I would choose less code instead of speed in 70% otherwise will never use jQuery:) – dmi3y Dec 10 '12 at 03:17
  • 4
    Worse than being slow, it's wrong. `sort` converts elements to strings first. The sorted output becomes: `[2, 3, 32, 32, 5, 56, 6, 89]` - you got lucky for this set but add a `9` in there and it will be calculated as the "largest". – Dennis Dec 10 '12 at 03:28
  • @Dennis, updated, though not such fast now – dmi3y Dec 10 '12 at 03:58
  • 1
    @dmi3y You're calling `sort` but you aren't actually sorting the array and providing the callback defeats the purpose you laid out for even using `sort` in the first place (multiple lines). Also, since you are only writing to `largest`, never actually reading it, you can't be checking for the largest value either. If you swap 32 and 89 you'll get the wrong answer, again. – Dennis Dec 10 '12 at 04:49
  • @Dennis, good one, updated – dmi3y Dec 10 '12 at 05:09
  • Actually reduce is both looking good and runs fast: ``` array.reduce((item, acc) => item > acc ? item : acc, array[0]) ``` You can check here: https://jsperf.com/array-sorting-javascript-stack/4 – Jaro Jun 04 '19 at 14:37
4

You have a few small mistakes. First:

if (array>largest) {

It should instead be:

if ( array[i]>largest) {

Second:

for ( i = 0; i <= largest; i++) {

should be

for (i = 0; i <= array.length; i++) {
zongweil
  • 1,981
  • 2
  • 20
  • 28
3
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= array[0];

for (i=0; i<=largest;i++){
    if (array[i]>largest) {
        largest=array[i];
    }
}
jermel
  • 2,316
  • 20
  • 19
2

You have two issues in your code. First, array>largest should be array[i]>largest. Second, you are declaring a new largest variable inside the if which isn't the same as the one outside. Remove var from the assignment of the new largest value.

tvanfosson
  • 509,016
  • 97
  • 693
  • 791