-2

i am getting a strange result using arr.sort() below is the code

const arr=[1,99,102,121,2,2,3,7]
arr.sort()
console.log(arr)

I am getting the following output

[
  1, 1000, 121,  2,
  2,    3,   7, 99
]

can someone please explain what is happening and why?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Also relevant: [How does Javascript's sort() work?](https://stackoverflow.com/q/1494713) | [Why doesn't the sort function of javascript work well?](https://stackoverflow.com/q/6093874) | [Array.sort() doesn't sort numbers correctly](https://stackoverflow.com/q/7000851) | [How to sort an array of integers correctly](https://stackoverflow.com/q/1063007) | [Why does numberArray.sort() not sort numbers correctly in JavaScript?](https://stackoverflow.com/q/11218670) | [Why do javascript sort a numeric array not in numeric order?](https://stackoverflow.com/q/19740047) – VLAZ May 08 '21 at 12:46
  • Have you read the [documentation of `Array.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)? It explains in the first paragraph that it sorts the values as strings. – axiac May 08 '21 at 14:59

2 Answers2

1

Array.sort accepts a function as parameter:

compareFunction Optional
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

You need arr.sort((a,b) => a - b)

Kobi
  • 135,331
  • 41
  • 252
  • 292
1

As stated in the docs

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Thus your values are converted to strings first and then compared lexicographic. Ie "101" is less than "2"

If you want to do a numerical sort, you have to provide a compare function

const arr=[1,99,102,121,2,2,3,7]
arr.sort((a,b) => a-b);
console.log(arr);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
derpirscher
  • 14,418
  • 3
  • 18
  • 35