Returning largest number with algorithm

Returning largest number with algorithm
0

#1

Tell us what’s happening:
Something wrong with my code, I can’t find what it is.

Your code so far


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

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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays/


#2

you need to follow the logic carefully to see the holes

Here’s what your code is doing:

1- Loop through all the given arrays. Let’s say the current array is [32, 35, 37, 39]
2- Loop through all the given numbers in the current array starting with ‘32’ in this case
3- let curLargest be the first number of the current array which is 32
4- is curLargest smaller than the current number 32 ? No.
5- Advance the inner loop to number 35
6- curLargest is still 32
7- is curLargest smaller than 35 ? Yes
8-So exciting! Remember 35!!!
9- Advance the inner loop to 37
10- curLargest is still 32
11- is curLargest smaller than 37 ? Yes!
12- So exciting! Remember 35 and 37!!
13- etc.

In the end you pushed 35, 37, 39 to ‘largest’ even though only 39 is largest…

add a console.log(largest); statemet to the loop and you will see it happening