Javascript not sorting numeric arrays correctly

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Javascript arrays have a sort method, but it does not sort numeric arrays as expected.  For example, this code …

javascript sort of numeric arrays

javascript sort of numeric arrays

sorts them as if they are string, rather than numeric as expected.  Weird.

Correct Way to Sort Numeric Arrays in Javascript

But fortunately, you can pass your own compare function to the sort method to get it to sort numeric arrays in a numeric fashion…

correct way to sort numeric arrays in Javascript

correct way to sort numeric arrays in Javascript

Now it will return the sortedArray as  [1, 4, 8, 10, 17].