Help me Return Largest Numbers in Arrays

Tell us what’s happening:

everything came out checked except the last largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3]. Can anyone tell me where i messed up?

Your code so far


function largestOfFour(arr) {
  var largestNumber = [0,0,0,0];// You can do this!
  for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++){
    for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++){
      if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]){
        largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
      }
    }
  }
  return largestNumber;
}

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; rv:66.0) Gecko/20100101 Firefox/66.0.

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

Your algorithm assumes the smallest number would always be zero. That is not the case in the last test case. You need to rethink your logic. You can solve this challenge with specifying a fixed lower bound.

Hint: Treat the first element in each sub array as the smallest.

2 Likes

It’s because of this line. You are initializing them with 0s and in the loop comparing them against 0. If you insert negative values, more specifically a negative value in your last item in the array, it will work.

For ex.

var largestNumber = [0,0,0,-Infinity];// You can do this!

1 Like