[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
Solved

# JavaScript: Sort Array Containing Mixture of Numerical Strings and Numbers

Posted on 2013-06-23
Medium Priority
294 Views
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(' | ') )
``````
0
Question by:hankknight
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 84

Accepted Solution

Dave Baldwin earned 2000 total points
ID: 39270050
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'.

http://www.w3schools.com/jsref/jsref_sort.asp
0

LVL 16

Author Comment

ID: 39270100
Thanks.
``````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(' | ') )
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
###### Suggested Courses
Course of the Month13 days, 10 hours left to enroll