Basic Algorithm Scripting - Return Largest Numbers in Arrays

Hello,
can someone tell me what is wrong with my code?

function largestOfFour(arr) {
  var myArr=[0,0,0,0];
  for (var i=0; i<arr.length; i++){
    
    for(var j=0; j<arr[i].length; j++){
if(arr[i][j]>myArr[i]){
  myArr[i]=arr[i][j];
}}

  }
  
  return myArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
  **Your code so far**
function largestOfFour(arr) {
var myArr=[0,0,0,0];
for (var i=0; i<arr.length; i++){
  
  for(var j=0; j<arr[i].length; j++){
if(arr[i][j]>myArr[i]){
myArr[i]=arr[i][j];
}}

}

return myArr;
}

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/105.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays

Link to the challenge:

can you describe your algorithm first? (how do you find the largest of 4?)

Yes. with for (var i=0; i<arr.length; i++), the loop starts to check each subarray and with for(var j=0; j<arr[i].length; j++) the inner loop starts to check objects within subarrays. I predefined an array of 0 objects, both loop will check if each number of subarrays is bigger than myArr, if so, myArr will change to that.

Thanks for that answer.

So the inner loop, tries to find the largest number in the current (i) array by comparing the value with 0 till it finds a bigger number.

Let’s say you have this
, [-72, -3, -17, -10]

How would your inner loop behave?

1 Like

ohhh I see, it will return 0 as it is bigger than all these.

1 Like

thank you so much, I think I found the glitch in my code.

1 Like