Return Largest Number in Array

Hello, I’m trying to figure out why my code isn’t working, I think I did everything fine.

function largestOfFour(arr) {
  let largest = 0;
  let largestArr = []
  for(let i = 0; i < arr.length; i++) {
    for(let k = 0; k < arr[i].length; k++) {
      if (arr[i][k] > largest) {
        largest = arr[i][k]
        largestArr.push(arr[i][k])
      }
    }
  }
  return largestArr;
}

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

Try this test case instead:

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

Still does not work.

Changing the test case will not somehow fix the problem in your code, no.

What do you see when you try the test case I suggested? What is the output of your function?

I get [4,5,1000,1001]

Never mind, I fixed it (looked at hints not solution)

There is the exact issue I wanted you to see.

? What did you mean?

4 isn’t the biggest in the first subarray

5 isn’t even in the second subarray

1000 isn’t in the third subarray

1001 isn’t in the fourth subarray

So this gives a hint as to what might be happening instead of finding the max in each subarray

1 Like