Hello and welcome to our community! Is this your first visit?
AdSlot7
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Need help to sort an array of strings and numbers

1. ## 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!

2. AdSlot6
3. 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.

4. 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>

5. 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.

6. if you don't like sort()'s mutation, use .slice().sort() to sort and get a fresh copy instead of the orig.

7. 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

8. Originally Posted by 123jo
And I don't want to use .sort...(the execution speed isn't an issue)
Why not? Is this homework of some kind?

9. If you want to sort without using sort() then you will need to implement your own sorting method.

10. Originally Posted by AndrewGSW
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>

11. Originally Posted by 123jo
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!

12. 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>

13. 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.

#### Posting Permissions

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