-1

I have a question regarding javascript's sort() function

var arr = [23,43,54,2,3,12];
arr.sort();

it's output is [12, 2, 23, 3, 43, 54] well it should be [2, 3, 12, 23, 43, 54]?

Chris Walsh
  • 3,423
  • 2
  • 42
  • 62
BILAL AHMAD
  • 686
  • 6
  • 14
  • https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly – aahhaa Sep 11 '17 at 18:02
  • 2
    Possible duplicate of [How to sort an array of integers correctly](https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly) – Brian Sep 11 '17 at 18:02
  • 1
    it's taking the first digit when sorting as your values represent strings – pokeybit Sep 11 '17 at 18:02

3 Answers3

3

It's because you're sorting the numbers with the default sorting algorithm, which converts them to a string and sorts lexicographically.

Instead pass a function defining a sort order via its return value.

var arr = [23,43,54,2,3,12]; 

console.log(arr.sort((a, b) => a - b));

Returning a positive number moves a toward the end of the list.

spanky
  • 2,768
  • 8
  • 9
2

You have to specify a sort function

[12, 2, 23, 3, 43, 54].sort(function (a, b) { return  a - b ; } )

The javascript specification states that sort should perform lexicografic sorting, docs

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
1

The sorting of number is based on Unicode. Hence the oder you have is correct. Refer the link for details.

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

Kniwx
  • 32
  • 6