0

I'm running into some issues with the javscript String() method.Consider the following example.

var myArray = [10,1,5,15];
myArray.sort();
console.log(myArray) //Logs 0,1,10,15,5 to the console

Is this an issue with the sort() method? Or is the string value of 10 and 15 actually less than the string value of 5?

1 Answers1

0

Yes sort is only sorting alphabetically. Below is alternative way of sorting

function sortNum(firstelement,secoundelement) {
    return firstelement - secoundelement;
}

var numArray = [10,1,5,15];
numArray.sort(sortNum);
Pragnesh Khalas
  • 2,908
  • 2
  • 13
  • 26