0

I tried to use sort function to arrange the items in order to find the largest element in a number array. In Chrome, inspect element and open the console.

>>var a = [1000, 1001, 857, 1]
>>undefined
>>a.sort()
>>(4) [1, 1000, 1001, 857] // no patern found.

Why did the numbers did not sort properly like they did for the other cases like these:

>>var b = [13, 27, 18, 26];
>>undefined
>>b.sort()
>>(4) [13, 18, 26, 27] // here the numbers are in ascending order.
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Harshit Pant
  • 1,032
  • 11
  • 14
  • 1
    The default comparator function compares values as strings, not numbers. You can pass your own comparator function. – Pointy Sep 12 '18 at 12:56
  • From the docs: `The default sort order is according to string Unicode code points.` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – briosheje Sep 12 '18 at 12:58

1 Answers1

1

That's because the default sort order treats the elements of the array as text, not numbers.

The default sort order is according to string Unicode code points.

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

Tim
  • 5,435
  • 7
  • 42
  • 62
  • That's well understood. Do you suggest I will not be able to use this sort function and i have to write my own? what is the use of the sort function in that case ? – Harshit Pant Sep 12 '18 at 13:00
  • That's only a default, you can provide your own function which takes in two elements and decides which one should be placed first in the array. The documentation is quite thorough in explaining how that function should behave. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description – Tim Sep 12 '18 at 16:05