Return Largest Numbers in Arrays TypeError: unknown: o is undefined

Tell us what’s happening:

Your code so far

function largestOfFour(arr) {
  let a = [];
  for(let i=0;i<arr.length;i++) {
    let max = arr[i][0];
    for(let j=0;j<arr[i].length;j++)
    if(arr[i][j] > max) max = arr[i][j];
    a[i] = max;
    max = 0;
  return a;

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0.

Link to the challenge:

TypeError: unknown: o is undefined

Your problem is with this line. arr[i] is undefined (a is just an empty array at this point) and you’re trying to access element 0 of undefined. You need to rethink your algorithm. Try using Math.max instead of trying to implement the max algorithm yourself, and the rest should be easy.

arr[i] is defined right? As arr is the parameter that is passed and a is an empty array.

Thank you for the other approach.

Also, i edited that line to max = -99999; and still getting typeError :frowning:

I apologize, I completely mis-read your algorithm, and confused a with arr. I’m still working out where the problem lies at this point.

1 Like

Try to use parenthesis around the code inside the for loop and if statement

Also, you don’t need to set max = 0 at the end of the loop - this wouldn’t get the error, it is just unnecessary

1 Like

Your approach works if you add {} to your inner loop so that your let j's scope is defined


Good catch @InternetFriend, it’s sometimes hard to see missing braces.

@Mithil467: I recommend always using curly braces for loops and if statements. Leaving them out can cause bugs that trip up even experienced programmers.

1 Like

Oh yes now it was accepted! Thank you very much! Thanks chuckadams for the other approach, thanks ieahleen and InternetFriend for the solution! I cannot mark both of your answers as solution though :frowning: .