0

Why does this return 10,5?

sort(5,10)

17th Apr 2020, 3:43 PM
Sajid
Sajid - avatar
7 Answers
+ 3
sajid chowdhury it's a default feature of sort function in JavaScript. Actually it is not sorting number. It's sorting string value means here numbers are considered as String and as you know that when we sort string it sort on character by character so here 1 is less than 5 that's why answer is (10, 5) If you want to sort in ascending or descending order Just do like this. [5, 10].sort(function (a, b) { return a - b }); [5, 10].sort(function (a, b) { return b - a });
17th Apr 2020, 4:13 PM
A͢J
A͢J - avatar
+ 1
sajid chowdhury Sort character by character like in your case 10 and 5, 1 is less than 5 so 10 will come first.
18th Apr 2020, 7:36 PM
A͢J
A͢J - avatar
+ 1
A J no I meant that I've to change default behaviour of sort method for numbers. But anyways thanks. I got my answer.
18th Apr 2020, 7:43 PM
Sajid
Sajid - avatar
0
Camcoder I asked why. I already know the solution. And the solution you gave is useless because I'm taking inputs from the user
17th Apr 2020, 3:50 PM
Sajid
Sajid - avatar
0
@so is 10,5 in ascending order?
17th Apr 2020, 3:53 PM
Sajid
Sajid - avatar
0
Camcoder if you don't know the answer why are you even replying
17th Apr 2020, 3:57 PM
Sajid
Sajid - avatar
0
A J so sort by default can only sort alphabets?
18th Apr 2020, 7:27 PM
Sajid
Sajid - avatar