Return Largest Numbers in Arrays 1

Tell us what’s happening:
only one test case is failing. please help. I think logic is ok, but I don’t know where am I failing.

Your code so far


function largestOfFour(arr) {
  // You can do this!
  var arr2=[];
  var d,j=0;
  for(var i=0;i<arr.length;i++){
     d=arr[i][j];
      for(j=0;j<arr[i].length-1;j++){
        if(arr[i][j+1]>d){
         d=arr[i][j+1];
        }
      }
    arr2.push(d);
  }
  return arr2;
}

console.log(largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays

So your problem is in the line I’ve marked:

  for(var i=0;i<arr.length;i++){
     d=arr[i][j];      // <------- THIS IS THE PROBLEM
      for(j=0;j<arr[i].length-1;j++){
        if(arr[i][j+1]>d){
         d=arr[i][j+1];
        }
      }
    arr2.push(d);
  }

First time through, works fine. Because j = 0 before the loop begins, right? Sure. Now, at the SECOND time through, hitting the SECOND array, j is NOT zero, it’s the index of the last element of the FIRST array. And that happens every time.

How might you fix that?

1 Like

Just don’t forget to declare loop variables with let. In the second loop you haven’t used the keywords, so it makes the variable global…

1 Like

Nah, j was defined as a var OUTSIDE the loop, so it has function scope. Not global.

1 Like

i got it ,i just declared j in second for loop as let j=0 ,it worked now it will always seek to var j=0,which was previously declared.

That, or simply change this line:

d=arr[i][j];

to

 d=arr[i][0]; 

In every case, you want the loop to start at its FIRST member, so using the variable j there adds a possible point where things could break. As a general rule, avoid referencing two variables of the same name in the same function scope (one in the function with a var, and one in inner loop with a let, but both with the same name and serving a similar purpose).

The confusion will bite you down the line.

1 Like

You are right, I didn’t even consider that the code was inside a function.

1 Like