Any Idea why this wont submit?

I tested this in the google chrome console and it seemed to work fine, but when I went to run the test only two of the 4 test arrays passed. Very confused.


function largestOfFour(arr) {
let newArr = [];
let highest = 0;
for (let i = 0; i < arr.length; i++) {
for (let z = 0; z < arr[i].length; z++) {
  if (highest < arr[i][z]) {
    highest = arr[i][z];
  }
}
newArr.push(highest)
}
return newArr;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 13597.66.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.109 Safari/537.36.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

You need to reset highest every time it goes in the second loop. Ideally scope of highest should be limited to first loop only.

for (let i = 0; i < arr.length; i++) {
    highest = arr[i][0]; // this change...
    // ideally you should declare highest here instead. like this: let highest = arr[i][z]; 
    for (let z = 0; z < arr[i].length; z++) {
        if (highest < arr[i][z]) {
          highest = arr[i][z];
        }
    }
    newArr.push(highest);
}
2 Likes

You’ve got two issues here. @piedcipher already gave you the first one.

The second issue is that you are assuming the numbers will always be positive, but @piedcipher’s solution will take care of that.

2 Likes


Anw, It’s not working fine in chrome console.

One last thing, the way you are going about this with nested for loops will definitely work but as you have already found out, it can be a little messy. What you are trying to do is find the max value in each sub array. Wouldn’t it be cool if there was a JS method you could use to do that for you.

2 Likes

You can couple this with map and spread operator and get 1 liner.

return arr.map(e => Math.max(...e));
1 Like

I know that, you know that, the objective is to get @lucas.h.cahill there without just giving the answer :slight_smile:

1 Like