Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New Coder
    Join Date
    Dec 2012
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Need help to sort an array of strings and numbers

    Hi, I need to sort an array of strings like ["DOWNc18","OUTc11","INc21","UPc0","SIDEc33"] in descending order of the numbers of each strings.
    At each step of my function, I add a string similar to those above in my array but it has to be in descending order. I do not want to use a sort function when all the elements of the array have been added. I want to sort one string at a time once it's added.


    Considering I have the integer of the element I'm about to add, but not those already added, here's a little part of what I did:

    Code:
    var result = [];
    var tab = ["DOWNc18","OUTc11","INc21","UPc0","SIDEc33"];
    //newInteger = 18, 11, 21, 0, 33...
    for(var i=0; i<tab.length; i++){
      if( newInteger[i] >= parseInt(result[0]) || result.length == 0 )
      {result.unshift(tab[i] + newInteger[i]);
      }
      else result.push(tab[i] + newInteger[i]);
      }
    }
    return result;
    By what could I replace the parseInt to get the integer in result[0]?
    (parseInt returns NaN here because the string doesn't start with an integer)

    Thanks for your help!
    Last edited by 123jo; 12-28-2012 at 03:54 AM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    If you really mean what you say, then I disagree with the conclusions you have reached re the preferred methodology.

    Consider this code:
    Code:
    <script type="text/javascript">
    var tab = ["DOWNc18","OUTc11","INc21","UPc0","SIDEc33"];
    var toAdd = [ "F1GG4", "2V7", "XXX1Z9" ];
    
    function sortOnNumeric( a, b )
    {
        return Number( b.replace(/\D/g,"") ) - Number( a.replace(/\D/g,"") );
    }
    
    var addWhich = -1;
    while ( true )
    {
        tab = tab.sort( sortOnNumeric );
        document.write( tab.join(" :: ") + "<hr>" );
    
        ++addWhich;
        if ( addWhich >= toAdd.length ) break; // out of the while loop
    
        tab.push( toAdd[addWhich] );
    
    }
    </script>
    Does that not do what you asked? Sort to descending order, both when the array is initialized *AND* each time an element is added?

    Or perhaps this is more in the spirit of what you are after???
    Code:
    <script type="text/javascript">
    var tab = [];
    
    function sortOnNumeric( a, b )
    {
        return Number( b.replace(/\D/g,"") ) - Number( a.replace(/\D/g,"") );
    }
    function addAndSort( addWhat )
    {
        tab.push( addWhat );
        tab = tab.sort( sortOnNumeric );
        return tab.join(" :: ");
    }
    
    
    var toAdd = [ "DOWNc18","OUTc11","INc21","UPc0","SIDEc33", "F1GG4", "2V7", "XXX1Z9" ];
    for ( var t = 0; t < toAdd.length; ++t )
    {
        document.write( addAndSort( toAdd[t] ) + "<br>" );
    }
    </script>
    Apologies for the obsolete document.write calls.
    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.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    And, finally, if you want something more reusable and encapsulated:
    Code:
    <script type="text/javascript">
    function sortByNumberArray( )
    {
        this.tab = [ ];
        this.sortOnNumeric = function( a, b )
        {
            return Number( b.replace(/\D/g,"") ) - Number( a.replace(/\D/g,"") );
        }
        this.addAndSort = function( addWhat )
        {
            this.tab.push( addWhat );
            return this.tab.sort( this.sortOnNumeric );
        }
    }
    
    // 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>
    Last edited by Old Pedant; 12-28-2012 at 06:27 AM.
    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.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    And if I failed to mention it...

    Calling the native sort() and passing in the sort ordering function is all going to one heluva lot faster than mucking with unshift and shift and all the rest.
    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.

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,188
    Thanks
    10
    Thanked 569 Times in 550 Posts
    if you don't like sort()'s mutation, use .slice().sort() to sort and get a fresh copy instead of the orig.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #6
    New Coder
    Join Date
    Dec 2012
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks for your answers! But, @Old Pedant, I don't really understand what does:

    Code:
    function sortOnNumeric( a, b )
    {
    return Number( b.replace(/\D/g,"") ) - Number( a.replace(/\D/g,"") );
    }
    And I don't want to use .sort...(the execution speed isn't an issue)

    Basically, what I'm looking to do is to 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. I can't think of any other way to sort an array in descending order without using .sort

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by 123jo View Post
    And I don't want to use .sort...(the execution speed isn't an issue)
    Why not? Is this homework of some kind?

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    If you want to sort without using sort() then you will need to implement your own sorting method.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by AndrewGSW View Post
    If you want to sort without using sort() then you will need to implement your own sorting method.
    For example:-

    Code:
    <script type = "text/javascript">
    
    function bubbleSort(arrayToSort) {
    for (var i = 0; i < len-1; i++) {		
    var t1 = arrayToSort[i+1].toString();
    t1 = t1.replace(/\D/g,"")*1;
    var t2 = arrayToSort[i].toString();
    t2 = t2.replace(/\D/g,"")*1;
    
    if (t1 > t2) {
    var temp = arrayToSort[i+1];
    arrayToSort[i+1] = arrayToSort[i];
    arrayToSort[i] = temp;
    }
    }
    }
    			
    function bubbleTest(arrayToSort) {
    var count = 0;
    while (count < len-1) {
    bubbleSort(arrayToSort);
    count ++;
    }	
    document.write('Iterations taken: ' + count + '<br>');
    document.write('The sorted array is now ' + arrayToSort + '<br>');
    }
    	
    var arrayToSort = ["DOWNc18","OUTc11","INc21","UPc0","SIDEc33", "FIG99", "GY43x", "KHc25"];
    var len = arrayToSort.length;
    document.write('The original array was ' + arrayToSort + '<br>');
    bubbleTest(arrayToSort);
    
    </script>
    Last edited by Philip M; 12-28-2012 at 07:21 PM. Reason: Noticed typo

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by 123jo View Post
    Thanks for your answers! But, @Old Pedant, I don't really understand what does:

    Code:
    function sortOnNumeric( a, b )
    {
        return Number( b.replace(/\D/g,"") ) - Number( a.replace(/\D/g,"") );
    }
    Okay...the .replace will replace all *NON DIGITS* (\D means non-digit, the /g means "all") with a blank string. So if b was "Z7X3JJ" all except the 7 and the 3 would be replace and the results would be "73". Do that to both of the arguments, subtract one from the other, and you have the classic way of sorting numbers. [The calls to Number( ) really aren't needed, since the subtraction will force conversion of "73" et al. to number 73 et al. anyway.]
    And I don't want to use .sort...(the execution speed isn't an issue)
    WHY? "Don't want to..." isn't a reason.

    Basically, what I'm looking to do is to 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. I can't think of any other way to sort an array in descending order without using .sort
    Pardon me, but that's NONSENSE. That will *NOT* sort the array!

    Take this example:
    Code:
    Add the number  7, 23, 19 to the array using your methodology:
    
    -- Start with the array empty: [ ]
    Add 7:  Nothing in the array, so 7 is the first element.  
    -- The array is now [7].
    Add 23: 23 is bigger than the first element (7), so it goes to front.  
    -- Array is now [23,7].
    Add 19: 19 is *NOT* bigger than the first element (23), 
            so ACCORDING TO YOUR RULES push it to the end.  
    -- The array is now [23, 7, 19].
    
    YOU ALREADY HAVE THE WRONG ANSWER!
    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.

  • #11
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts

    Lightbulb

    This is a goofy way to do it, but a possibility.
    Note: No entry error checks. Just an example.
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8" />
    <title> Untitled </title>
    <script type="text/javascript">
    var sarr = [];
    function goofySort() {
      var p = 0;  var flag = false;
      var entry = document.getElementById('entry').value;
      if ((sarr.length-1) < 0) { sarr.push(entry); } else {
        if (entry <= sarr[0]) { sarr.unshift(entry); } else {
          if (entry >= sarr[sarr.length-1]) { sarr.push(entry); }
          else { 
            p = 1;  flag = false;
            while ((p < sarr.length) && (flag == false)) {
              if ((entry > sarr[p-1]) && (entry <= sarr[p])) { sarr.splice(p,0,entry); flag = true; }
              p++;
            }
            if (flag == false) { sarr.push(entry); } // not sure if this is really neede
          }
        }  
      }
      document.getElementById('debugger').innerHTML = sarr.join(',');
    }
    </script>
    
    <style type="text/css">
    
    </style>
    </head>
    <body>
    <input type="text" id="entry" value="">
    <button onclick="goofySort()">Goofy Sort</button>
    <div id="debugger"></div>
    </body>
    </html>

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    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
    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.
    Last edited by Old Pedant; 12-29-2012 at 10:13 PM.
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •