Return Largest Numbers in Arrays Negative Numbers Assistance

Return Largest Numbers in Arrays Negative Numbers Assistance
0

Tell us what’s happening:
I know that it is not taking the challenge largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3] because of the negative numbers. Can someone help me understand how to change ‘var largestNumber = [0,0,0,0];’ so it takes a negative number? I tried ‘var largestNumber = [ ];’ and it did not work.

Your code so far


function largestOfFour(arr) {
   var largestNumber = [0,0,0,0];
   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 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36.

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

Try using -Infinity instead of zero for your largestNumber array.

Thank you so much for your response! Could you assist me on how to input -Infinity after the largestNumber array? Should it be inside of the brackets?

Sorry for the simple question, I am a newbie and I don’t want to go directly to the answer and input it, I want to fix what I did wrong so I make sure I don’t repeat the same mistake.

Why not just assume the first number of each sub array is the largest?

I figured it out by doing what you said!
‘largestNumber = [-Infinity, -Infinity, -Infinity, -Infinity];’

If I took that approach, would I need to sort the array first to ensure the largest number is the first number?

It is best to stick with @chuckadams’ suggestion. My approach does not use an array of largest numbers to start with, so it is completely different algorithm.