Why is the inbuilt JavaScript method sort() not sorting the array properly?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the inbuilt JavaScript method sort() not sorting the array properly??

I was trying to sort out the elements of an array in an ascending order and i used the code snippet arr.sort(), it actually sorted the array but not in ascending or descending order as expected

31st Dec 2020, 8:24 PM
Rex Nerdy
Rex Nerdy - avatar
2 Answers
+ 3
I assume you mean something like [2,12,6,8,10,4].sort() leading to [10, 12, 2, 4, 6, 8]? The reason for this is both simple and... rather annoying. The default sort() method in JavaScript does not sort by numerical values, but instead sorts it alphabetically (lexographically). While numerically, the above list should be sorted to [2,4,6,8,10,12], in alphabetical order, 10 comes first. If you want it to sort by number, you'll need to do something akin to what Med Amine Fh has done, and specify your own comparison function. In particular, the comparison function parameter for sort(): 1. Has two parameters, A and B, which basically stand for two elements next to each other. 2. Must return either a positive number, a negative number, or zero. - If it returns a positive number then A comes before B - If it returns zero, leave the elements where they are with respect to each other - If it returns a negative number, then swap the elements (B comes before A).
3rd Jan 2021, 7:46 PM
HealyUnit
HealyUnit - avatar
0
arr.sort((a,b)=>a-b)
31st Dec 2020, 8:27 PM
Med Amine Fh
Med Amine Fh - avatar