Return Largest Numbers in Arrays (using a loop declarative)

Hi guys, I’m having a hard time understanding this code below.

The points have been commented out below. I appreciate the help.

function largestOfFour(arr) {
  // You can do this!
  const results = [];
  for (let i=0;i<arr.length;i++) {
    let largestNum = arr[i][0]; // // --> ** what's with the [0]? **
    for (let j=1;j<arr[i].length;j++) {  // --> ** why we let j = 1? **
      if ( largestNum < arr[i][j]) {
        largestNum = arr[i][j];
      }
    }
    results[i]=largestNum; // --> ** why's withe results[i]? and when it I tried to reverse it {largestNum=results[i] it does not work the same} **
  }
  return results;
}

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

Cheers!

Hi @CoDean, just a curiosity, did you wrote this code, or is something you found?

Anyway a little bit about this function.

1: largetNumber is used as a variable for comparison, that gets initialised to the first element of the sub-array on each iteration.
This is to avoid an erroneous comparison between a number, and a largestNum you don’t know yet.
So here the author decided to initialise it to the first element in the subarray so that at least the comparison makes sense

2 - Why j = 1?
Well, since in the previous step we decided that at least for the first time largestNum is the first element in the sub-array, makes sense to start comparing the number at least from the 2nd entry, hence j =1.

3 - Why result[i] = largestNum?
Here the author decided to write in result Array in the same index as the one looked upon.
Pretty much equivalent to `results.push(largestNum)

Hope this helps :+1: