Return Largest Numbers in Arrays.Help

Return Largest Numbers in Arrays.Help
0

#1

Tell us what’s happening:
What is going wrong there?

Your code so far


function largestOfFour(arr) {
var answer = [];
  for (var i=0; i<arr.length; i++) {
    var biggestNumber = 0;
    for (var sl = 0; sl < arr[i].length; sl++){
      if(arr[i][sl] > biggestNumber) {
        biggestNumber = arr[i][sl];
      }
    }
    answer[i] = biggestNumber;
  }  
 // You can do this!
 return answer;
}

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/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays/


#2

Your code resets biggestNumber to zero when checking a new sub array. If all of the numbers in a sub array are negative, your code logic would say that zero is the largest number instead of the largest negative number in the sub array.

For example, if you had the following sub array: [ -100, -6, -15, -30], the largest number is -6, but your code would say the largest number is zero. Think about how you can compare each number to itself in each sub array instead of assuming the smallest number possible is zero.


#3

function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
}

results[n] = largestNumber;

}
// You can do this!
return results;
}

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

This is my new code.I belive it is right.


#4

Does it pass the tests? If so, it appears you have solved the challenge. Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.

I know I have explained this many times in the past, so can you please learn how to put 3 backticks on the line before and after any code you post, so that it properly displays on the page?

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


Thank you.