Return Largest Numbers in Arrays help

Return Largest Numbers in Arrays help
0

#1

Whats wrong with my code?? Its not working

function largestOfFour(arr) {
// You can do this!
var myArr = [];

var maxValue = 0;

for (var i=0; i<arr.length; i++){
   
  for ( var j=0; j<arr[i].length; j++){
   
    if (arr[i][j]>maxValue){
      maxValue = arr[i][j];
      if (j==3){
        myArr.push(maxValue);
      }
    }
  }
  
} 

return myArr;
}

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


#2

The inner if-block is not always executed. It’s only tested when arr[i][j] > maxValue, which isn’t always true per iteration of the inner loop.

Also, the maxValue at any given time refers only to the max value of the current subarray. So it makes sense to reset it before running the inner loop.


#3

@riteshprk: A couple things I noticed. For one, it’s unclear to me (maybe just me) what purpose the “if (j==3) {}” statement serves; I think it can be removed and it will still work just fine.

Also, another way to say what @kevcomedia is saying is that the .push() needs to come between the loops–so after the closing brace for the [i] loop and before the closing brace for the [j] loop. And then the return statement comes inside the function but after the [i] loop. Hope this helps.


#4

thanks @kevcomedia and @Ailokin for your suggestion. Your advise help me to write correct code. Thanks.


#5

If you haven’t yet discovered repl.it, it is very helpful in trial-and-error programming and using console.log to track the program’s process. Here’s my repl.it solution to this Free Code Camp “Return Largest Numbers” problem: https://repl.it/DhhK/12. You can comment/uncomment the three different versions to see how they run.


#6

If you’re in doubt, or the FCC console gives weird results, try your code there on repl.it.


#7

Thanks @kevcomedia for the link. It is very handy for debugging code. I would like to use console.log() function to get intermediate result in the code but unfortunately it didn’t work in freecodecamp and also at the link repl.it.
you have provided. Could you please advise how to use it.


#8

It’s @Ailokin who gave the link in the first place. I just made a follow up :slight_smile:

console.log should work. You just type in plain old JS code and anything in console.log should be printed. For example, paste this in repl.it

function double(n) {
    return 2 * n;
}

var x = double(5);
var y = double(7);
console.log(x); // 10
console.log(y); // 14

console.log(double(10)); // 20

and check out the link above. To run the code, press ctrl+enter


#9

Hello @kevcomedia I have just checked didn’t get expected result at console,log(). See the link https://repl.it/Dkch/0


#10

@kevcomedia sorry my mistake. It is working.