JavaScript: Sort Array Containing Mixture of Numerical Strings and Numbers

Posted on 2013-06-23
Last Modified: 2013-06-23
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

Question by:hankknight
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
  • Learn & ask questions
LVL 83

Accepted Solution

Dave Baldwin earned 500 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'.
LVL 16

Author Comment

ID: 39270100
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


Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Anyone familiar with PhotoSwipe? 3 19
selected value 16 26
How to pass values to HTML-5 attribute dynamically? 24 51
Table header must be on top 2 31
This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question