Return Largest Numbers in Arrays help for Fanty

Return Largest Numbers in Arrays help for Fanty
0

#1

Tell us what’s happening:
So I’m not sure why this isn’t passing. Specifically, in the test shown, it pulls 13 from the first sub array and returns it as the biggest value for the second subarray.

I know this is probably not an efficient way to get to a solution, but it’s what I came up with on my own and the fact that it almost passed makes me happy! Any input as to why this isn’t working, as well as a better way to do/condense this, would be greatly appreciated! :slight_smile:

Your code so far

function largestOfFour(arr) {
  var biggest1 = 0;
  var biggest2 = 0;
  var biggest3 = 0;
  var biggest4 = 0;
  var result = [];
  
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].length; j++) {
      if (arr[0][j] > biggest1) {
        biggest1 = arr[i][j];
      } 
      if (arr[1][j] > biggest2) {
        biggest2 = arr[i][j];
      }
      if (arr[2][j] > biggest3) {
        biggest3 = arr[i][j];
      }
      if (arr[3][j] > biggest4) {
        biggest4 = arr[i][j];
      }
    }
  }
  result = [biggest1, biggest2, biggest3, biggest4];
  return result;
}

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

#2

I took your solution and added several console.log statement so you could see what is happening. It is best to view/run the code on the repl.it site.


#3

Ah okay, so if I’m understanding this correctly, my code is faulty in that it would only work if the sub arrays contain numbers that are larger than the sub arrays before it. Interesting.

What would you suggest in terms of a fix? Perhaps resetting the variables somewhere, but I’m not sure how that would given that I am returning the variables in array form.

Thanks for taking a look btw, still consider myself super new to coding.


#4

With your current code structure, you only want to check make comparisons for biggest1 when you are dealing with the first element (when i = 0). For biggest2, when you are dealing with the 2nd element (when i = 1), etc…

See if this hint gets you closer.


#5

I figured out a way and tried it just as you replied! I changed the [i] in all the if statements to [0], [1], etc and it worked! Thanks a lot for the help. I’ll peruse the answers that other people submitted to see if I can do it a simpler/cleaner way :stuck_out_tongue: