-2

I have an array having values are 1,10,6,8,7 and I want to sort this using sort() method, It's giving result like this 1,10,6,7,8 rather than 1,6,7,8,10

I wrote code below :

var arr = [1,10,6,8,7];
arr.sort();
document.write(arr);

Snap code

Can anyone have idea about this?

Hidayt Rahman
  • 2,490
  • 26
  • 32
  • 2
    It reads 10 not as ten, but as one zero. Maybe this is helpful? stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly – Pixeldenker Jan 24 '17 at 12:10
  • Refer this link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – RaR Jan 24 '17 at 12:10

5 Answers5

2

10 is before 2 in unicode. You need to help the sort() function to determine which element is before which.

arr.sort(function(a, b) {
  return a - b;
});
Ahmad
  • 12,336
  • 6
  • 48
  • 88
2
var scores = [1, 10, 21, 2]; 
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.

Refer this link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

RaR
  • 3,075
  • 3
  • 23
  • 48
0

From the documentation:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order.

This is why sort on an array of number is "weird": because it compares the string representation of the numbers.

In a unicode point of view: "10" < "2".

Derlin
  • 9,572
  • 2
  • 32
  • 53
0

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Original answer:

https://stackoverflow.com/a/7000924/7462678

Community
  • 1
  • 1
LS_85
  • 238
  • 1
  • 7
0

According to the Mozilla Developer Network, "The default sort order is according to string Unicode code points.". 10 comes before 2 in Unicode code point order. You would need to pass in a comparison function to the sort function, which would compare the numbers.

Array.prototype.sort - Mozilla Developer Network

Patrick Kayongo
  • 545
  • 1
  • 5
  • 11