-2

array.sort((a,b)=>a-b))

when I use the sort() method to numbers array, what kind of rules do they use to pick a and b from the numbers array?

when I log the a and b in the console, it seems to show array[1] as b, array[0] as a and so on, but when the array is different, it shows different rule.

Is there any way to see how sort()method pick the arguments from the numbers array?

array will be like [2,20,60,300,1000] or longer.

Thank you.

Minju Kim
  • 3
  • 1
  • 6
    This is implementation dependent. JavaScript engines are free to choose which comparison-based sort implementation they use, so you can get different results on different engines. It should not be of any concern. An algorithm should not depend on it. – trincot Jan 30 '22 at 17:51
  • See [Sorting / compare in Chrome vs Firefox](/q/64396555/4642212). – Sebastian Simon Jan 30 '22 at 17:52

1 Answers1

0

The sort function is a native function, it means that it is implemented by the browser javascript engine in language X ( c++ or java usually ) and you cannot edit or modify them.

If you want a custom sort function you need to write your own or find one that fits your needs.

Why you need to know how the sort function manage the given array?

Mike M
  • 71
  • 5
  • I wondered how JS chose the a and b from the array on what kind of base. – Minju Kim Jan 30 '22 at 18:00
  • You should dig into browser source codes if the code is open....what I know is that these native functions are not always the most performant because the purpouse is also to manage any possible adge case. – Mike M Jan 31 '22 at 09:03