Return Largest Numbers in Arrays Help!

Tell us what’s happening:
Please can someone tell me why is this code not working and returning null. Thank you

Your code so far

  var largestNums = []; 
  for (i = 0; i < arr.length; i++){
    var sorted = arr[i].sort(function(a, b){return a - b;});
    var largestNum = sorted[i][-1];
    largestNums.push(largestNum);
  }
  console.log(largestNums);
  return largestNums;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36.

Link to the challenge:

Sorted is an array with the sorted initial array, the largest number is the leng of the sorted array less 1 (the last number).
You must not use the iterator with it.

 function largestOfFour(arr)
 {
 var largestNums = []; 
  for (i = 0; i < arr.length; i++){
      
    var sorted = arr[i].sort(function(a, b){return a - b;});
    
    //This line looks at the last number in the sorted array
    var largestNum = sorted[sorted.length-1];  
    largestNums.push(largestNum);
  }
  console.log(largestNums);
}

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

Output : [5, 27, 39, 1001] 

Correct me if I am wrong , but the OP maybe coming from python ? where array[-1] can be used to get the last element of an array in python. However this doesn’t work in javascript, @JScars has shown , where to find the last element of an array , array[length-1] is used.

1 Like

You got it right that’s from Python.

Ok I fix it by changing it to this:

function largestOfFour(arr) {
  var largestNums = []; 
  for (i = 0; i < arr.length; i++){
    arr[i].sort(function(a, b){return a - b;});
    var largestNum = arr[i][arr.length-1];
    largestNums.push(largestNum);
  }
  console.log(largestNums);
  return largestNums;
}

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

Thank you so much for your help!