Basic Algorithm Scripting - Return Largest Numbers in Arrays

output should be [5,27 39, 1001] but output comes [ 5, 27, 18, 26, 35, 37, 39, 1001 ]
my dry run says [ 5,27,39,1001] but instead console outputs [ 5, 27, 18, 26, 35, 37, 39, 1001 ]

Your code so far

function largestOfFour(arr) {
  let result = [];
  for(let i in arr){
 let max = arr[i][0];

    for(let j=1;j< arr[i].length;j++){

    if(arr[i][j] > max ){
      result.push(arr[i][j])
    }
    }
  }
  console.log(result)
  return result;
}

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

Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays

Link to the challenge:

What dry run? Can you be a little more specific about how you are getting [ 5,27,39,1001]?

If you wrap a console.log around the last line:

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

You clearly get [ 5, 27, 18, 26, 35, 37, 39, 1001 ].

Also, you are doing this at the very beginning of each outer for loop:

let max = arr[i][0];

And then you never change the value of max again and you compare it against every other number in the subarray. Do you see how max is always going to stay the same value and thus you are going to get a lot of numbers bigger than it?

1 Like

bro
function largestOfFour(arr) {
let result = ;
for(let i in arr){
let max = arr[i][0];

for(let j=1;j< arr[i].length;j++){

if(arr[i][j] > max ){
  result.push(arr[i][j])
}
}

}
console.log(result)
return result;
}
you understand

No. Your function does not produce [5,27 39, 1001] for that function call, it produces [ 5, 27, 18, 26, 35, 37, 39, 1001 ]. So what dry run did you use to get [5,27 39, 1001]?

You are pushing every element in the subarray that is greater than the first element of the subarray into the result array, not the max element of the subarray.

bro after the end of second for loop it should again assign max = arr[i][0] then compare other elements in arr[i][j] if arr[i][j] > max then max = arr[i][j]

yes bro I got it thank you very much

You don’t have this in your code.

function largestOfFour(arr) {
let result = ;
let max = 0;
for(let i=0;i<arr.length;i++){
max = arr[i][0];

for(let j=1;j< arr[i].length;j++){

if(arr[i][j] > max ){
  max = arr[i][j];
  
}

}
result.push(max)
}
console.log(result)
return result;
}

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

Don’t post solutions!

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