Largest number in array's

Why is the last array pushing 0 as the largest number in the last array?

function largestOfFour(arr) {
  let result = [];
 
  for (let x = 0; x < arr.length; x++) {
    let trackNum = 0;
    let subA = arr[x];
    for (let y = 0; y < arr[x].length; y++) {
      let num = subA[y]; 
      if (num > trackNum) trackNum = num;
      
    }
    result.push(trackNum);
  }
  
  return result;
}


console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));

You set trackNum to 0. When you check if num > trackNum, none of the numbers in the last array pass because they are all negative.

1 Like

You don’t have to create a guess with zero knowledge. If I was to look at the first element of the array, what’s a really good guess for what the largest element is?

1 Like