Return Largest Numbers in Arrays ! solution please?

Return Largest Numbers in Arrays ! solution please?
0.0 0

#1

Tell us what’s happening:

This code is not working, why???

Your code so far

function largestOfFour(arr) 
{
  var arr2=[];
     
  // You can do this!
  for(var i=0;i<arr.length;i++)
  {
    
    arr[i].sort();
   
    for(var j=0;j<arr[i].length;j++)
    {
      if(j===arr[i].length-1)
      {
        arr2.push(arr[i][j]);
      }
      
    }
  }
  
  return arr2;
}

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 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:


#2

Why .sort() function not working in the last sub-array?


#3

you need a compare function 4 ur .sort() mdn docs;
when compared as strings 857 is larger than anything starting with 1


#4

think youll need to use sort like this

var numbers = [1000,1001,857,1];
numbers.sort(function(a, b) {
  return a - b;
});

you can read about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Better way to do things would be using Math.max()