DEV Community

Lama Al Rajih
Lama Al Rajih

Posted on

Explain This Like I'm Five

So, I've been doing freeCodeCamp for a while, and I need an explanation for the following:

function largestOfFour(arr) {
  var results = [];
  for (var n = 0; n < arr.length; n++) {
    var largestNumber = arr[n][0];
    for (var sb = 1; sb < arr[n].length; sb++) {
      if (arr[n][sb] > largestNumber) {
        largestNumber = arr[n][sb];
      }
    }

    results[n] = largestNumber;
  }

  return results;
}
Enter fullscreen mode Exit fullscreen mode

This is the beginner's solution provided by FCC, and I wrote the correct solution, but my code is wrong and I don't understand why there's a need for var results or for var largestNumber. Why can't I return arr[n][sb] as is?

Top comments (5)

Collapse
 
alephnaught2tog profile image
Max Cerrina • Edited

What did you write as your solution?

I think I can guess what the issue is and your confusion. I can't see the prompt, but the way it's written it looks at first like they want you to find a single value--the max out element, the ultimate max of an array of arrays, for example. At first glance that's what I thought until I read it more carefully--it looks like they want you to give an array of the max elements of arrays. So, at first glance:

const arrayGroup = [
    [1,2,3,4],
    [2,4,6,8],
    [3,6,9,12],
    [32,44,66,11]
];

// what I expected was
largestOfFour(arrayGroup); // => 66

// what they wanted was
largestOfFour(arrayGroup); // => [4,8,12,66]

You can't return arr[n][sb] as is for two reasons in the above code:

  1. (arr[n][sb] > largestNumber) being true means that element is currently larger than the largestNumber and all other elements that have preceded it--but NOT the elements after. Imagine you had an array [1,2,3,4] -- 2 is larger than 1, but if you return that then since you've found a larger number, you miss the others. You've proved that it is larger but not THE largest since you have no knowledge at that point of the numbers after it.

  2. ... I forgot what number two is. :P

FWIW, I found it confusing too; both the first time I did something like that last semester and in reading their code. Also I don't love their naming style....

Anywho:

// their code, annotated by me
function largestOfFour(arr) {
        var results = [];

        // loop through our arrays
        for (var n = 0; n < arr.length; n++) {

            // make largestNumber the first item of the array
            var largestNumber = arr[n][0];

            // compare it to the other items in that same arr
            for (var sb = 1; sb < arr[n].length; sb++) {

                // if the currentNumber is bigger than the largestNumber
                // then it itself is the new largest number we compare to.
                if (arr[n][sb] > largestNumber) {
                    largestNumber = arr[n][sb];
                }

            }

            // add it to our results array
            results[n] = largestNumber;
        }

        // return the array
        return results;
    }

// ====================================================================

// how I'd write it...
// longer, but clearer, I think!
function howIdWriteIt(groupOfArrays) {
        var largestNumberArray = [];

        // loop through our arrays
        for (var whichArray = 0; whichArray < groupOfArrays.length; whichArray++) {
            var currentArray = groupOfArrays[whichArray];

            var largestNumber = currentArray[0];

            for (var whichNumber = 1; whichNumber < currentArray.length;
                 whichNumber++) {

                var currentNumber = currentArray[whichNumber];

                if (currentNumber > largestNumber) {
                    largestNumber = currentNumber;
                }

            }

            // add it to our largestNumberArray array with the same index as the array we're on -- so it matches up
            // ie, the 0th entry in largestNumberArray is the max number of the 0th array
            largestNumberArray[whichArray] = largestNumber;
        }

        // return the array
        return largestNumberArray;
    } 

// and if you wanna test...!
    const arrayGroup = [
        [1,2,3,4],
        [2,4,6,8],
        [3,6,9,12],
        [32,44,66,11]
    ];

    console.log(largestOfFour(arrayGroup));
    console.log(howIdWriteIt(arrayGroup));

Collapse
 
alephnaught2tog profile image
Max Cerrina

And for good measure, what I had thought they wanted and how I would've written it:

function getMaxOfAllArrays(groupOfArrays) {
        var largestNumberArray = [];
        var largestNumber = 0; // picking 0 to start

        // loop through our arrays
        for (var whichArray = 0; whichArray < groupOfArrays.length; whichArray++) {
            var currentArray = groupOfArrays[whichArray];

            // index change -- since we are no longer comparing within the array
            // we need to loop through the whole thing.
            for (var whichNumber = 0; whichNumber < currentArray.length; whichNumber++) {

                var currentNumber = currentArray[whichNumber];

                if (currentNumber > largestNumber) {
                    largestNumber = currentNumber;
                    // we can't stop here--what about the other arrays?
                }
            }
        }

        // return the max
        return largestNumber;
    }
Collapse
 
lamaalrajih profile image
Lama Al Rajih

The problem:

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].

My solution:

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];
}
}
}

Why do I need to have an empty bracket set for largestNumberArray, per your example? I'm not exactly clear on that part.

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!