Return Largest Number - Console.log

Tell us what’s happening:

I’ve created a function to push the largest number from a series of sub-arrays into a new array. Everything seems to be working fine. I’ve used console.log() as you’ll see in the comment. Am I overlooking something really simple?

Your code so far


let largestNumArr = [];

function largestOfFour(arr) {
for (let i = 0; i < arr.length; i++) {
  let currentNum = arr[i][0];
  for (let j = 0; j < arr[i].length; j++) {
    if (arr[i][j] >= currentNum) {
    currentNum = arr[i][j];  
      
    }
  }
  largestNumArr.push(currentNum);
} 
console.log(largestNumArr); //this is logging the correct array but I'm not meeting that criteria according to the checkboxes 
return largestNumArr;

}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
2 Likes

Okay, I think that makes sense. So what you’re saying is that I was actually getting an array that looked like this:

[ 5, 27, 39, 1001, 27, 5, 39, 1001, 9, 35, 97, 1000000, 25, 48, 21, -3] 

instead of this:

[ 5, 27, 39, 1001 ]
[ 27, 5, 39, 1001 ]
[ 9, 35, 97, 1000000 ]
[ 25, 48, 21, -3 ]

Exactly! So once you bring your largestNumArr variable inside of your function, your code should work.

1 Like

Thank you so much! :slight_smile:

1 Like