Help pls - Return Largest Numbers in Arrays

Hi all, I’m having problems with the following task. Would love some help?
We are asked to return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

function largestOfFour(arr) {
  // You can do this!
  var answer = [];
  for (var i = 0; i < arr.length; i++) {
     var biggestNumber = 0;
    for (var sI = 0; sI < arr[i].length; sI++) {
      if (arr[i][sI] > biggestNumber) {
        biggestNumber = arr[i][sI];
    answer[i] = biggestNumber;

  return answer;

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 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:

Hi there!

The initial value of the variable “biggestNumber” is equal to 0.

So, the code wil not work for an array of negative numbers, because the number 0 is always larger than any negative number (-1, -3, etc.)

1 Like

hey, it is great you want to help, but maybe people would learn more if you give hints and point out errors, instead of just saying what the solution is

what happens if the biggest number in the array is negative?

think of what you could put instead of 0 here

1 Like

Thank you guys. That’s very helpful. Unfortunately I’m just starting out at coding, and I have no idea what to put there instead. Any hints? I’ll have a google.

you can do two things,

  • or use the values you have there,
  • or use the lowest possible mathematical value in js, negative infinity

(I suggest you try to use both, just for practice)

Yessss, just done it! Used Math.max()
Many thanks to you both.

Another approach is to assign a undefined value and change the if to: (arr[i][sI] > biggestNumber || biggestNumber == undefined)

1 Like

Well, with Math.max() it works, but it’s not the best option.

This option is better. Just change this

var biggestNumber = 0;

to this

var biggestNumber = arr[i][0];
1 Like

Thank you again guys. I’ll play around with those options.

1 Like