Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort an array of mixed content

Status
Not open for further replies.

pintofbest

Programmer
Nov 23, 2006
1
GB
I have an array which contains a mixture of strings and numbers representing an address line. For example "20 Main Street" etc

I have found examples of functions which sort alphabetically or which sort numerically. Using the alphabetic sort would mean that for example "16 Main St", would come before "2 Main Street".

Does anyone have an example of a function which would sort this kind of mixed data satisfactorily?

Thanks in advance
 
Here is some sample code to illustrate how you can use your own sort method to do just this...
Code:
<script type="text/javascript">
var myArray = [
	'10 ten',
	'5 five',
	'1 one',
	'2 two',
	'12 twelve'
];

function sortMyArray(a, b) {
	var numA = parseInt(a.substring(0, a.indexOf(' ')), 10);
	var numB = parseInt(b.substring(0, b.indexOf(' ')), 10);
	if (numA < numB) return -1;
	if (numA > numB) return 1;
	return 0;
}
</script>
You can test the sorting using a link like this (note that the function name for my sort function is emboldened below and passed into the sort method):
Code:
<a href="javascript:alert(myArray.sort([b]sortMyArray[/b]));">Sort Array</a>

Hope this works out for you!

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top