Return Largest Numbers in Arrays - return the correct answer however can't pass the challenge

Return Largest Numbers in Arrays - return the correct answer however can't pass the challenge
0

#1

Tell us what’s happening:

Your code so far

function largestOfFour(arr) {
  // You can do this!
  for(i=0;i<arr.length;i++){
    arr_2.push(Math.max.apply(null,arr[i]));
}
  return arr_2;
}
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36.

Link to the challenge:


#2

Based on the code you have, it is not possible to return the correct answer because you are trying to use the push function on a variable (arr_2) which has not been declared as an array.

You should be getting an error message in the console (Ctrl + Shft + I in Chrome browser) like:

ReferenceError: arr_2 is not defined

#3

Hi!

Thanks for answering my question, I’ve included that statement originally indeed.

Please see screenshot.

Many thanks!


#4

It needs to be declared inside your function, because each time the function is called, arr_2 will still have what it had from the previous call to the function plus whatever gets push on the current call to the function. It retains the values between calls to the function, because it was declared in the global scope.

What you really want is for each test to start with a blank array for arr_2, which is what happens if you move it into the function.

In general, try to not use global functions unless you “know” for sure that other functions won’t be effected by what you declare globally.


#5

Hi!
Thanks for taking the time! But the goal of the exercise is to return the array of the large numbers…so seems like it’s reasonable to declare it globally. As from the print screen, the output was correct.

Thoughts?

Thanks!


#6

It might seem reasonable, but you will not pass the tests declaring arr_2 globally. It will only pass the 1st test. After that arr_2 will have what ever was in it after the previous test and then are pushing more and more items into it on subsequent test.

The result that shows in the simulated console is just for the call to the function at the bottom of your code section. That is the correct answer and that is why you passed the first test, because the first test happens to be the same function call.


#7

Got it, thanks!

I was able to pass the challenge.

Thank you for taking the time to answer my question.


#8

how did you know to use math.max.apply?