Ehhh...it can be done simpler than that. Plus the following code handles them mixed text and numbers as in the original request. (Not that doing so would be hard with jmrker's code, of course.)
Code:
<script type="text/javascript">
function sortByNumberArray( )
{
this.tab = [ ];
this.getVal = function( txt )
{
return Number( txt.replace(/\D/g,"") );
}
this.addAndSort = function( addWhat )
{
var addVal = this.getVal( addWhat );
var newtab = [];
for ( var t = 0; t < this.tab.length; ++t )
{
if ( addWhat != null && addVal > this.getVal( this.tab[t] ) )
{
newtab.push( addWhat );
addWhat = null;
}
newtab.push( this.tab[t] );
}
if ( addWhat != null ) { newtab.push( addWhat ); }
this.tab = newtab;
return this.tab;
}
}
// and all the rest of this is to demonstrate use of the above
var sorter1 = new sortByNumberArray( );
var sorter2 = new sortByNumberArray( );
var toAdd1 = [ "DOWNc18","OUTc11","INc21","UPc0" ];
var toAdd2 = [ "SIDEc33", "F1GG4", "2V7", "XXX1Z9" ];
for ( var t = 0; t < toAdd1.length; ++t )
{
document.write( "sorter1: " + sorter1.addAndSort( toAdd1[t] ) + "<hr>" );
document.write( "sorter2: " + sorter2.addAndSort( toAdd2[t] ) + "<hr>" );
}
</script>
This is close to the spirit of what 123jo wrote when he said
Quote:
|
see if the string I'm about to add has an integer bigger than the first one in the result array. If it does, put it at the beginning of the array; if not, push it at the end
|
Indeed, the integer is checked to see if it is bigger than the "first one" IN WHAT REMAINS OF THE ORIGINAL ARRAY (not the entire array, which is where 123jo really messed up). And, if it is, then that integer is put at the beginning OR THE REST of the original array. In other words, I fixed his broken algorithm by looking at the original array element by element instead of as a whole.