Return Largest Numbers in Arrays, Math.max & spread

Hello,

I’m trying to find a solution based on what I’ve learned so far. The following works, but I’m curious as to why this works on only four sub-arrays? If I add another array (which I’ve done here) the function does not apply to it. Can someone please explain why?


function largestOfFour(arr) {
let newArr = []
for (let i = 0; i < arr.length; i++){
  for (let j = 0; j < arr[i].length; j++){
    newArr.push(Math.max(...arr[j]));
  }
  return newArr;
}
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], [7, 8, 9, 10]]));

Your browser information:

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

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

please explain what your second loop is doing

Okay, so I worked out a better solution using a for…of loop, which as I understand, is built for objects and arrays.

function largestOfFour(arr) {
  let newArr = []
  for (let i of arr){
      newArr.push(Math.max(...i)); 
  }
  return newArr;
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], [7, 8, 9, 10]]));

I understand now why I dont need the second loop. But I still don’t understand why my first attempt worked on only four arrays.

What type or error did you see when your used more than 4 sub-arrays? I don’t see any reason why it wouldn’t work.

I don’t get an error. It just doesn’t log the fifth array. (or sixth or seventh etc.)

If I try it with three of fewer arrays I do get the following error:

TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method. 

I don’t know enough yet to fully understand what this means or why it occurs.

What do you mean by ‘doesn’t log the fifth array’? What output do you get?

Ah, I see it. You are pushing max(...arr[j]) and then you are returning inside of the i loop. Your logic is a bit mixed up. You don’t want to return inside of a loop in this case!

And with that j loop, you are going to check as many arrays as arr[i].length, which is different that arr.length.

This line probably isn’t doing what you want to do.

Thank you. I think that makes sense now.

Am I correct in thinking arr[i].length is always 4 because there are four numbers in each sub-array?

That’s correct. That’s why you were always only doing the j loop 4 times.

1 Like

Thanks for the help. :+1:

1 Like