** Explanation Needed ** Return Largest Numbers in Arrays

Link to challenge:

Solution:

function largestOfFour(arr) {
  let results = [];
  for (let i = 0; i < arr.length; i++) {
    let largestNumber = arr[i][0];
    for (let j = 1; j < arr[i].length; j++) {
      if (arr[i][j] > largestNumber) {
        largestNumber = arr[i][j];
      }
    }
    results[i] = largestNumber;
  }

  return results;
}

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

Could someone please explain to me the following code:

for (let j = 1; j < arr[i].length; j++)

Why is j = 1?

Thanks in advance.

In this case j = 1 because a variable (largestNumber) was already declared with an initial β€œ0” value, which will be later compared on the if statement as follows:

if (arr[i][1] >arr[i][0] )

It’s my first time trying to explain code, hopefully I did well.

2 Likes

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