Basic Algorithm Scripting - Return Largest Numbers in Arrays; Dealing with negative numbers?

Tell us what’s happening:
So I’m struggling trying to find a way for this to work for the case of an array with negative numbers. I don’t know if I should make a new variable or set newHigh to something different in the for loop. I just don’t know how to deal with negatives aside from setting my newHigh to -10000000000 but that’s just ridiculous to do.

Your code so far

function largestOfFour(arr) {
  let newHigh = 0;
  let newArr = [];
  //indexes the  input Array
  for (let arr1 = 0; arr1 < arr.length; arr1++){
    //this goes into the subindex of the array
    for (let arr2 = 0; arr2 < arr[arr1].length; arr2++) {
        //stores current value
         let currentHigh = arr[arr1][arr2];
         if (newHigh < currentHigh) {
           newHigh = currentHigh;
        }
    } 
    newArr.push(newHigh);
    newHigh = 0;   
  }return newArr;
  //console.log(newArr);
}
  
largestOfFour([[-2, -5, -3, -9], [13, 27, 18, 26], [10, 12, 15, 19], [1000, 1001, 857, 1]]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0

Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays

Link to the challenge:

Is there a reason you have to start newHigh at 0? For each sub array you are going through each of the four numbers to figure out which one is the largest. So if you start with the first number in the sub array, isn’t that the newHigh for the sub array?

1 Like

That was indeed the case. It’s funny I tried to do that earlier and it didn’t work because I stored it in the wrong spot so I thought it wouldn’t work but your comment made me try it again. Thank you for the advice.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.