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);
4
  • The largest number of an empty array should be -Infinity. Commented Dec 10, 2012 at 2:40
  • Simplest Way: var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]); Commented Nov 3, 2020 at 6:41
  • 2
    const array1 = [1, 3, 2]; console.log(Math.max(...array1)); // expected output: 3 Commented Jun 21, 2022 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()). Commented Jun 30, 2023 at 18:17

6 Answers 6

42

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

Sign up to request clarification or add additional context in comments.

4 Comments

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 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?
Here's a jsperf I modified with additional test cases. 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.
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);
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);

6 Comments

Don't redeclare largest in the if statement. You've already declared the var in the opening under array.
This shouldn't be the accepted answer since there are more efficient ways to do this.
This fails when the first array item is 0 or negative. It also fails if the array starts with two 1s or three 2s or so on.
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.
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);
|
24

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

9 Comments

Cool, but sorting is slower.
@LarryBattle compare with what? here is jsperf jsperf.com/array-sorting-javascript-stack, the only drowback here is if you have null defined elements, but need to check though
This is a VERY inefficient method. js array sorts are rather slow. jsfiddle.net/ychWw In my simple testing, method1 completes in around 50ms, while your method takes 5 seconds.
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".
@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.
|
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++) {

Comments

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];
    }
}

1 Comment

this is re-declaring largest inside the loop instead of assigning it
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.

1 Comment

Math.max(...array)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.