4

I'm trying to use JavaScript's sort function on arrays of numbers and sometimes it doesn't do anything:

var a = [200,20].sort(); // [20,200]
var b = [200,21].sort(); // [200,21]

jsfiddle

pythonian29033
  • 5,148
  • 5
  • 31
  • 56
nima
  • 6,566
  • 4
  • 45
  • 57

2 Answers2

5

Javascript sorts everything as strings (=alphabetically) by default. The string "200" is less than the string "21". To sort as numbers you have to tell it so:

[200,21].sort(function(a,b) { return  a-b })
georg
  • 211,518
  • 52
  • 313
  • 390
  • This code can be shortened using an [Arrow Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). `numberArray.sort((a, b) => (a - b));` Yay! **Note: check if your JS engine supports Arrow Functions.** – Константин Ван Dec 28 '15 at 09:54
0

Yep, this is the standard behaviour for "sort" because it perform "string" reordering. If you want to sort by number value you must pass a "compare" function to sort, like this:

[200,21].sort(function (a, b) {
  return a-b; 
})
// [21, 200]

The function must return 0 for identical value, n < 0 if a < b and n > 0 if a > b. For that reason, the difference is enough to provide sorting (assuming that you're not using huge numbers)

ArtoAle
  • 2,939
  • 1
  • 25
  • 48