Last array keeps displaying wrong order

I am trying to sort each of the arrays in the largestOfFour array and for some reason, the last arry keeps ordering it wrong like this [1, 1000, 1001, 857]

what am I doing wrong?

function largestOfFour(arr) {

var newarr = arr[0].sort();
var newarr2 = arr[1].sort();
var newarr3 = arr[2].sort();
var newarr4 = arr[3].sort();

return newarr4;

}

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

.sort() treats array elements as strings by default (so those numbers that start with 1 go first regardless of numeric value, etc.). You’ll have to pass it a function so it sorts them as numbers.

From MDN:

To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn’t contain Infinity and NaN):

function compareNumbers(a, b) {
  return a - b;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

1 Like