Return Largest Numbers in Arrays - Not working

Return Largest Numbers in Arrays - Not working
0

#1

Tell us what’s happening:

Because it is specified that sub-arrays will contain no more than 4 elements, after comparing every element of sub-arrays to the previous ones and landing on the last one that is assigned to “biggest” binding, i push that one into array of bigs.
But something’s not working. Could someone tell me what it is?

Your code so far


function largestOfFour(arr) {
  // You can do this!
  let biggest = 0;
  let arrOfBigs = [];
  for (let i = 0; i < arr.length; i++){
      for (let j = 0; j < arr[i].length; j++){
      if (arr[i][j] > biggest){
        biggest = arr[i][j];
      }
      if ( j == 4) {
        arrOfBigs.push(biggest);
      }
      }
    }
  return arrOfBigs;
}

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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


#2

Notice that this will never execute because the lengths of arrays are 4. Remember first element starts at index 0?
so 0, 1, 2, 3. At index 3 is where you reach the end of the loop.


#3

totally missed that! I should’ve replaced it with “length of the sub array” so that it would be more adaptable to bigger and smaller sub-Arrays. thanks!


#4

That’s good idea. But make sure it’s length of the subarray -1. :slight_smile:


#5

thanks. I noticed few more problems - for example, after one subArray is looped over, “biggest” binding is still in the memory, so with the next sub array, every element of that one is compared to the previous “biggest”, instead of 0, as i want them to be. i fixed that by moving “let biggest = 0” to inside first (upper, i guess?) for loop, so that it gets set to 0 at the start of each iteration.

And setting it to 0 by default also fails when i have to compare to negative numbers. i could just set it to - 10000 instead, but that’s rather dumb solution :slight_smile:


#6

Yeah since there are negative numbers in the subarrays so using 0 as pivot doesn’t make sense. I would just use Math.max method and use spread operator to find the biggest numbers in each sub array.


#7

Instead of setting biggest = 0 or -10000, why not set biggest = arr[i][0] (the first element in each sub array?


#8

I eventually looked at FCC solution and that’s how they did it, so i adapted it :slight_smile: