Return Largest Numbers in Arrays - Not working

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

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.

1 Like

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!

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

1 Like

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:

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.

1 Like

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

it doesn’t work, and say can’t read property 0 of undefined

If you have a question about a specific challenge as it relates to your written code for that challenge, just click the Ask for Help button located on the challenge. It will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.

1 Like