Biggest four numbers in array help

Hello, in this part I need to find the biggest four numbers and return them in an array.
Why is my code is not working?

  my code:

function largestOfFour(arr) {
let first=0,sec=0,thrd=0,fourth=0;

for(let i=0;arr.length > i;i++){
  for(let j=0;4>j;j++){
    if(arr[i][j] > first){
      first = arr[i][j];
    }else if(arr[i][j] > sec){
      sec = arr[i][j];
    }else if(arr[i][j] > thrd){
      thrd = arr[i][j];
    }else if(arr[i][j] > fourth){
      fourth= arr[i][j];
    }
    

  }
}
let newArr =[];
newArr.push(first);
newArr.push(sec);
newArr.push(thrd);
newArr.push(fourth);
return newArr;
}

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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 OPR/80.0.4170.91

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

Hi @denizozcanmc !

Welcome to the forum!

Your current approach is not going to work and there is a simpler way to do this.

I would suggest resetting the lesson.

If you are going to use the nested for loop approach you only need 1 if statement.
Not 4.
Slowly walk through the logic of this problem and see if you can solve this with just 1 statement.

You don’t need 4 variables all initialized to 0.

You just need one variable inside the for loop that will keep track of the largest num of each sub array.
Also, you don’t want to initialize this variable with 0.
reason being is because some of the sub arrays have negative numbers and you have to account for that.

Then you can push that largest num to the new arr.

function largestOfFour(arr) {
  //create new empty arr
  for (let i = 0; arr.length > i; i++) {
    //largest num variable goes here
    for (let j = 0; 4 > j; j++) {
      //condition goes here
    }
    //add largest num to new arr
  }
  //return new arr
}

Try to slowly walk through the logic and implement an easier approach to the problem than your current code.

Hope that helps!

2 Likes

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