Replace this line...
[a.substring(1)*1, b.substring(1)*1]
... with ...
[parseInt(a.substring(1), 10), parseInt(b.substring(1), 10)]
... and it will work (demo), though the sorting function still won't be as universal as possible.
Explanation: a.substr(1)*1
(better written as just +a.substr(1)
, btw) casts that substring into Number
type. In theory, that should give you a real number. In JS practice, however, it'll fail (giving NaN
) if the rest of the string is not a complete representation of a number, having nothing except but that number.
For example, for 2620-48-PoEP
line, '620-48-PoEP'
is cast to Number
. Now JS cannot interpret it as 620
- it'll be too bold for it, as there are some other meaningful (=non-whitespace) characters there. So instead of giving you 620
, it gives you NaN
.
Now, any comparison between NaN
and NaN
is false (expect !=
) - and that'll essentially make your sorting function gone haywire.
As a sidenote, array.sort
updates the object in-place - you don't need to use another reference to it (a2
variable), you can work with a1
.