I have a bug in my code please help!

I don’t seem to find out where it went wrong…I would much appreciate your comments
Desired Output: [27,5,39,1001]
Output Displayed: [ 27, 27, 39, 1001 ]

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

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

Two questions for you

  1. Why set max to 0 at first?

  2. What should happen to max when you switch sub arrays?

look closely to your output, the numbers always increase which are the values of max variable, focus on that.

The following are my understandings:
Ans 1: to initialize the variable
Ans 2: should it be reset to zero?

I know you are initializing the value to 0. But why use 0?

You need the max of each subarray, so yea, I’d reset in between subarrays.

how else shall I initialize the value?
oh I see, although resetting the value of max to zero between subarrays worked for the non negative inputs, one of my tests still didn’t pass. what could be the reason behind this?

Following was the input:

largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])

Well, 0 is bigger than everything in that subarray.

Personally, I’d make the initial ‘guess’ for the max something that you know is in the subarray.

Thank you for your response.

what if i don’t know what is going to be provided as an input? what value do I assign to max so that it can pass the test with array containing numbers like -9999999999999?

You always have the subarray though

Hint: arr[i][0] will always be no bigger than the biggest thing in the subarray


I’m not a big fan of using Number.NEGATIVE_INFINITY personally. There is a more sensible initial guess that results in you doing a bit less work.

Yeah, you could always use the numbers in the given array for the assignment, that is better and more optimized.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.