Help with debugging javascript loop

I am trying to return the largest number in an array, everything works fine but for this particular array that returns a number that is not even in the loop. I need help figuring out what I am doing wrong.

Here is my code (I have also added the log statements for easy debugging)

function largestOfFour(arr) {

    var resultArr = []
    var largest = 0
      for (var i = 0; i < arr.length; i++){
        console.log('parent arrays ------', arr[i])
         for (var j = 0; j <  arr[i].length; j++){
           console.log('child array -----', arr[i][j])
           if(arr[i][j] > largest){
             largest = arr[i][j]
           console.log('here is the largest-----', largest)
    return resultArr;
    console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

This text will be hidden

Consider this: the first item in the array. At that point, you have nothing bigger than it, and nothing smaller than it.

Rather then setting largest to 0, try setting largest to the first item in an array, then loop from the second item to the end of the array. That way you know largest is at least in range.

Now… Can you figure how to loop from the second one? :grin:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.