Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-28-2012, 03:48 AM   PM User | #1
123jo
New Coder

 
Join Date: Dec 2012
Posts: 10
Thanks: 2
Thanked 0 Times in 0 Posts
123jo is an unknown quantity at this point
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..
123jo is offline   Reply With Quote
Old 12-28-2012, 06:02 AM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,172
Thanks: 59
Thanked 3,994 Times in 3,963 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
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.
Old Pedant is offline   Reply With Quote
Old 12-28-2012, 06:24 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,172
Thanks: 59
Thanked 3,994 Times in 3,963 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
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>
__________________
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-28-2012 at 06:27 AM..
Old Pedant is offline   Reply With Quote
Old 12-28-2012, 06:33 AM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,172
Thanks: 59
Thanked 3,994 Times in 3,963 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
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.
Old Pedant is offline   Reply With Quote
Old 12-28-2012, 08:11 AM   PM User | #5
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,452
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.8% IE9:11.4% IE10:6.5%
rnd me is offline   Reply With Quote
Old 12-28-2012, 04:12 PM   PM User | #6
123jo
New Coder

 
Join Date: Dec 2012
Posts: 10
Thanks: 2
Thanked 0 Times in 0 Posts
123jo is an unknown quantity at this point
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
123jo is offline   Reply With Quote
Old 12-28-2012, 04:55 PM   PM User | #7
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Old 12-28-2012, 05:03 PM   PM User | #8
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
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
AndrewGSW is offline   Reply With Quote
Old 12-28-2012, 05:38 PM   PM User | #9
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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>
__________________

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.

Last edited by Philip M; 12-28-2012 at 07:21 PM.. Reason: Noticed typo
Philip M is offline   Reply With Quote
Old 12-28-2012, 07:57 PM   PM User | #10
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,172
Thanks: 59
Thanked 3,994 Times in 3,963 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
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.]
Quote:
And I don't want to use .sort...(the execution speed isn't an issue)
WHY? "Don't want to..." isn't a reason.

Quote:
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.
Old Pedant is offline   Reply With Quote
Old 12-29-2012, 04:32 AM   PM User | #11
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,763
Thanks: 29
Thanked 453 Times in 447 Posts
jmrker will become famous soon enough
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>
jmrker is online now   Reply With Quote
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,172
Thanks: 59
Thanked 3,994 Times in 3,963 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
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:02 PM.


Advertisement
Log in to turn off these ads.