0

I have following array

temp =  [1230, 900, 1000, 2130, 2400]

and used temp.sort() to sort it by value and when see it using console.log its gives following

[1000, 1230, 2130, 2400, 900]

this supposed to be done like

[900, 1000, 1230, 2130, 2400]

is there anything wrong or need to use some other method ?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Vikram
  • 3,171
  • 7
  • 37
  • 67
  • 1
    [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort): "If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order." – Andreas Oct 16 '15 at 12:25

1 Answers1

1

You should use compareFunction of Array.prototype.sort()

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

var temp = [1230, 900, 1000, 2130, 2400];
temp.sort(function(a, b) {
  return a - b;
})

snippet.log(temp)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • As an explanation: the sort function sorts by Unicode code points by default, and `9` comes after `2` in that case. – Jacob Oct 16 '15 at 12:25
  • 1
    From the duplicate: _The compare function should return -1, 0 or +1. a>b will only return true or false_ – mplungjan Oct 16 '15 at 12:26