DEV Community

Discussion on: Explain This Like I'm Five

Collapse
 
aurelkurtula profile image
aurel kurtula

Why can't I return arr[n][sb] as is?

Because the function would stop there!

function test(){
  var i = 1; 
  return i;
  i = 2;
}

i never turns 2, the function stops/dies once return runs. Now here is an array:

const arrayGroup = [
  [1,12,13,4],
  [2,4,16,8]
];

And this is your solution (you provided in the comments)

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

Line two loops through the parent array, largest becomes 1. Then in line 4 we try to loop through the first child array ([1,12,13,4]). The if statement, the first time checks if 1 (child array, first value) is bigger than 1, it's not. Then it check if 12 (child array, second value) is bigger than 1, it is. Then it return 12. END OF CODE.

That's why you can't return arr[i][j].

Now if we do not return it, but instead replace the large number we have something like this

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

By the time the loops are done largest will end up being 16. So if the task was to find the largest number in all the arrays that would work (scoping problems excluded).

What we need though is to return the largest number from each array

function largestOfFour(arr) {
  var results = [];
  for (i = 0; i < arr.length; i++) { // loop 1
    var largest = arr[i][0];
    for (j = 0; j < arr[i].length; j++) { // loop 2
      if (arr[i][j] > largest) {
        largest = arr[i][j];
      }
    }
   // this runs only when loop 2 finishes (continuation of loop 1)
   // largest will be a13, then a 16
   results[i] = largest
  }
  // this  runs when loop 1 finishes
  return results 
}

results[i] = largest stores the larges number from the first array, then the largest number from the second array (plain english). Then, knowing that there are no more arrays to check, those two big numbers are return (at the end of all the operations)

Collapse
 
lamaalrajih profile image
Lama Al Rajih

Thank you! This was so helpful and cleared it up for me!