Return Largest Numbers in Arrays - Need an error explanation please

function largestOfFour(arr) {
  var larnumArr = []
  var larnum = 0;
for (var i = 0; i < arr.length; i++) {
  if (arr[i][i] > larnum) {
    larnum = arr[i][i];
  }
  larnumArr.push(larnum)
}
  return larnumArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]))

Here’s the code I typed. When logging console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])), I have the following output [ 4, 27, 37, 37 ].

The 37 shows up twice at the end of my array, but it should outputs 1001 to get it right.
While im near the solution, I can’t see where my mistake is in the code?

Does anybody have a clue ?

what is going on here?

1 Like

What’s going on here is your for loop does not loop through each element of each inner-array like it is supposed to, it instead loops through the ith element of the ith array. That means it loops through the first element of the first array, then the second element of the second array, then the third of the third and the forth of the forth, it ignores all the rest.

Another problem is that your larnum variable is not being reset back to zero as you check each inner-array so by the time you get to the fourth array, larnum is still 37 (the third element of the third array) and your code checks if larnum is bigger than the fourth element of the fourth array, and since 37 is not bigger than 1, your code leaves larnum as it is and pushes 37 to the larnumArr to represent the largest number in the 4th array. This is very wrong though since 1001 is the largest number in the 4th array, not 37, and 37 is not even in the 4th array.

1 Like

hi, i used the same letter for both the index and subindex

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