Basic Algorithm Scripting: Return Largest Numbers in Arrays [Negative Numbers Test Case]

Hi guys, I was able to get all test cases correct except for the last one which included and array with all negative numbers. This is my current code:

function largestOfFour(arr) {
  let finalArray = [];
  for(let i = 0; i < arr.length; i++){
    let num = 0;
    for(let x = 0; x < arr[i].length; x++){
      if(arr[i][x] > num){
        num = arr[i][x]
      }
    }
    
    finalArray.push(num)

  }
  return finalArray;
}

I just can’t seem to find a way to quantify and keep track of the “greatest” of the negative numbers in an array.

Thanks.

You need to change this, as after this you compare each number of the array to this and negative numbers will never be bigger than 0

1 Like

How would I be able to handle that part of the code (negative numbers)?

actually, never mind. I ended up finding out that there was a -Infinity “number” in this language. So I ended up using it in my new code:

function largestOfFour(arr) {
  let finalArray = [];
  for(let i = 0; i < arr.length; i++){
    let pastNum = -Infinity;
    for(let x = 0; x < arr[i].length; x++){
      let currentNum = arr[i][x];
      if(currentNum > pastNum){
        pastNum = currentNum
      }
      else if(currentNum < pastNum){
        // Do nothing
        pastNum = pastNum;
      }
    }
    
    finalArray.push(pastNum);

  }
  return finalArray;
}
1 Like

No need for -Infinity for this challenge. Just assume the first item in each array is the largest and compare the rest to it.

1 Like