Saturday, 16 October 2021

Javascript Array Sort. Surprise!

What is the output for the below


arr = [3,20,17,2,12,15,17,4,15,20]
arr.sort()
console.log(arr)

The out put is:

[12, 15, 15, 17, 17, 2, 20, 20,  3,  4] 

The reason is that for this built in sort function, it will converting the elements into strings before do sorting! This is the only language I find so far to do such a stupid thing

To sort integer in the expected order, do that


//will out put [2,  3,  4, 12, 15, 15, 17, 17, 20, 20]
arr = [3,20,17,2,12,15,17,4,15,20]
arr.sort((a,b) => a-b)
console.log(arr)

No comments:

Post a Comment