Solved

JavaScript: Sort Array Containing Mixture of Numerical Strings and Numbers

Posted on 2013-06-23
2
245 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
2 Comments
 
LVL 82

Accepted Solution

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

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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…

747 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now