?
Solved

JavaScript: Sort Array Containing Mixture of Numerical Strings and Numbers

Posted on 2013-06-23
2
Medium Priority
?
288 Views
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

0
Comment
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
  • Learn & ask questions
2 Comments
 
LVL 84

Accepted Solution

by:
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

by:hankknight
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(' | ') )

Open in new window

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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

This article discusses how to create an extensible mechanism for linked drop downs.
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
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

765 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