View Single Post
Old 12-29-2012, 10:04 PM   PM User | #12
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,234
Thanks: 59
Thanked 3,997 Times in 3,966 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.

Last edited by Old Pedant; 12-29-2012 at 10:13 PM..
Old Pedant is offline   Reply With Quote