Skip to content
Advertisement

Sort an array of alphabetic and numeric string-type elements ASC, but with numeric elements after alphabetic elements

I have an array of values which are either all-letters or all-numbers and need to sort them in an ascending fashion. Additionally, I want all-numeric values to be moved to the end of the array so that they occur after all of the non-numeric values.

JavaScript

If I run sort() on it I get:

JavaScript

but I’d like to see:

JavaScript

I tried array_reverse(), but that didn’t seem to change anything. I’m at a loss for how to get the numbers last, but in ascending order.

Advertisement

Answer

What you need is sort but with a custom comparison function (usort). The following code will get it done:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement