23

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,738
  • 21
  • 105
  • 131
George Agusta
  • 341
  • 1
  • 2
  • 4
  • The largest number of an empty array should be `-Infinity`. – Ja͢ck Dec 10 '12 at 02:40
  • Simplest Way: var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]); – Siddhartha Mahato Nov 03 '20 at 06:41
  • 1
    const array1 = [1, 3, 2]; console.log(Math.max(...array1)); // expected output: 3 – Danish Jun 21 '22 at 13:48
  • @SiddharthaMahato That sorts them lexicographically, not numerically. You need to pass a numerical comparison function to `.sort()`. `(a, b) => a - b` for ascending or `(a, b) => b - a` for descending (which would also let you drop the `.reverse()`). – Darryl Noakes Jun 30 '23 at 18:17

6 Answers6

40

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

for (var i = 0; i < arr.length; i++) {
  if (arr[i] > largest ) {
    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

Gangula
  • 5,193
  • 4
  • 30
  • 59
Larry Battle
  • 9,008
  • 4
  • 41
  • 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
27
var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;

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

console.log(largest);
Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Yamaha32088
  • 4,125
  • 9
  • 46
  • 97
  • 1
    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
  • 5
    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
  • the for loops needs to run while `i – oliver_siegel Jul 27 '22 at 19:21
23

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
  • 5,600
  • 2
  • 38
  • 44
dmi3y
  • 3,482
  • 2
  • 21
  • 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 (let i = 0; i < array.length; i++) {
Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
zongweil
  • 2,031
  • 2
  • 21
  • 30
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,326
  • 21
  • 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
  • 524,688
  • 99
  • 697
  • 795