Please explain Return Largest Numbers in Arrays

Tell us what’s happening:
Hello, why would this code function when called with [[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]] return 25,48,21,0 which cannot be found anywhere instead of 25, 7, 34, 48 which is a close match ?

Your code so far


function largestOfFour(arr) {
  // You can do this!
var result = [];
for (let i=0; i < arr.length; i++) {
  var largest = 0;
  for (var ir=0; ir < arr[i].length; ir++) {
  if (arr[i][ir] > largest) {
   largest = arr[i][ir];
  }
  }
   result[i] = largest;
}
  return result;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36.

Link to the challenge:

I think you haven’t quite got the instructions. The function doesn’t return the ‘largest’ array of the four supplied, it returns the largest number in each of those arrays - as an array.

So, in array 1, it finds 25, in array 2 it finds 48, etc. These four largest numbers are returned as an array. In array 4 (the one with all the negatives) it returns 0 because you declared largest to be zero and none of the array items were greater than (>) it

From the challenge:

Return an array consisting of the largest number from each provided sub-array.

From the sub-array [17, 23, 25, 12], which number contained within is the largest?
Now, from the sub-array [25, 7, 34, 48], which number contained within is the largest?

Apply this line of questioning to all the sub-arrays and you should get

  • 25
  • 48
  • 21
  • -3

From the last result, we can see that the largest number could have a negative value.
The following bit of code shows why you’re getting 0 instead of -3 for your last value.

  var largest = 0;
  for (var ir=0; ir < arr[i].length; ir++) {
  if (arr[i][ir] > largest) {
   largest = arr[i][ir];
  }
  }
   result[i] = largest;

You should look into using the .map() method here.