0

Hi. What do you think, in what order will the numbers be and why?

const arr = [ 2, 13, 26, 8, 10]; arr.sort(); console.log(arr);

3rd Jul 2020, 6:59 AM
Михаил
2 Réponses
+ 2
The sort() method takes an additional optional argument, which is the compare function. If the compare function is not provided, then all the numbers are converted to strings and are sorted lexicographically. So we need to provide the compare function to sort the numbers. const arr = [ 2, 13, 26, 8, 10]; arr.sort(function(a, b) { return a - b; }); console.log(arr); Visit the below link for further details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
3rd Jul 2020, 8:23 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
It appears that the array elements were treated as string instead of number. The elements ordering seems to be performed lexicographically. But I can't answer the "why" part (sorry)
3rd Jul 2020, 7:28 AM
Ipang