Basic Algorithm Scripting - Return Largest Numbers in Arrays

Tell us what’s happening:
my code passes the test but im curious if I can put a better number or special character to the value of largest number because I just bruteforced it and assigned -100 as value

Your code so far

function largestOfFour(arr) {
  let largestNumbers = [];
  var largestNumber = -100;
  for(let a = 0; a < arr.length; a++){
    for(let b = 0; b < arr[a].length; b++){
      if (arr[a][b] > largestNumber){
        largestNumber = arr[a][b];
      }
    }
    largestNumbers.push(largestNumber);
    largestNumber = -100;
  }
  return largestNumbers;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [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/116.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays

Link to the challenge:

can I have a value such as negative infinity

var largestNumber = -100;

Instead of assigning a random value, how about assigning the first value of the sub-array just before the second for loop. Such that:

  let largestNumber;
  for(let a = 0; a < arr.length; a++){
    largestNumber = arr[a][0]; //(*)
    for(let b = 0; b < arr[a].length; b++){
      if (arr[a][b] > largestNumber){
        largestNumber = arr[a][b];

As you go through each member of the sub-array, if the current number is higher than the one that you assigned, it will be replaced, and so on…

Now you won’t have to worry about the range of numbers in the array.

*Imagine if one of the subarrays had values ranging from -400 to -200!

To strictly answer your question though, I believe that this is what you are looking for:

1 Like

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