• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 300
  • Last Modified:

JavaScript: Sort Array Containing Mixture of Numerical Strings and Numbers

How can this be sorted correctly?

var coords = [1,'3',7,8,'9',11,'12',15,17,'19',25,'27','44','49',111,'112',188,'199'];
alert( 'Unsorted: '+coords.join(' | ') +'\nSorted: '+ coords.sort().join(' | ') )

Open in new window

1 Solution
Dave BaldwinFixer of ProblemsCommented:
What do you mean by 'sorted correctly'?  When you mix number and text formats like that, you will probably have to do something to put them all in the same format.  If you make them all numbers, you can sort in numerical order where 44 would come before 111.  If you make them all text, then '111' would come before '44'.

hankknightAuthor Commented:
var coords = [1,'3',7,8,'9',11,'12',15,17,'19',25,'27','44','49',111,'112',188,'199'];
alert( 'Unsorted: '+coords.join(' | ') +'\nSorted: '+ coords.sort(function(a,b){return a-b}).join(' | ') )

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now