Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Feedback on: irt.org FAQ Knowledge Base Q341, on November 14, 2001 at 19:41:40:

You are here: irt.org | About | Feedback | 3325 [ previous next ]

Feedback on:
irt.org FAQ Knowledge Base Q341

Sent by
Bill Wilkinson on November 14, 2001 at 19:41:40:

Worth:
Worth reading

Length:
Too long

Technical:
Not technical enough

Comments:
It's a nice article to show the differences between the different kinds of sorts. But *WHY* would you *EVER* code a sort in JavaScript (slow interpreted code) when the JS language has Array.sort built in????

Most especially, JS has Array.sort(userCompareFunctionName) built in!

By specifying a comparison function that understands that it is comparing subarrays of "multi-dimensional" array [a lie...it's actually an array *of* arrays], the job is done instantly! And all the ugly sorting code, per se, is left to the presumably *much faster* JS library to accomplish!

Want an example? I'll try pasting it here. If it doesn't come across pretty, email me.

<HTML><BODY>

<SCRIPT Language="JavaScript">

var arryTest = new Array(
new Array(1, 'test', new Date('11/07/2001') ),
new Array(3, 'nothing', new Date('11/09/2001') ),
new Array(67, 'bar', new Date('11/12/2001') ),
new Array(56, 'foo', new Date('2/02/2001') )
);

// sortIndex *MUST* be a global variable!
var sortIndex = 0;

// This function satisfies the requirement of the
// function that can be passed to Array.sort, per
// the ms docs at
// http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthsort.asp
function compareByIndex( subar1, subar2 )
{
var val1 = subar1[sortIndex];
var val2 = subar2[sortIndex];
if ( val1 == val2 ) return 0;
if ( val1 > val2 ) return 1;
return -1;
}

function sortBy( ix )
{
sortIndex = ix; // set subarray index to sort by!
sorted = arryTest.sort( compareByIndex ); // do it!
// rest of this is just to demo it worked:
msg = "Sorted array:\n"
for ( var n = 0; n < sorted.length; ++n )
{
var subar = sorted[n];
msg += ( subar[0] + ", " + subar[1] + ", "
+ subar[2] + "\n" );
}
alert( msg );
// return not used in this demo
return sorted;
}

function getRadioValue( rbgroup )
{
for ( var i = 0; i < rbgroup.length; ++i )
{
if ( rbgroup[i].checked ) return rbgroup[i].value;
}
return -1;
}
<FORM>
Sort by column:
<INPUT Type=Radio Name=which Value=0 Checked> 0
<INPUT Type=Radio Name=which Value=1> 1
<INPUT Type=Radio Name=which Value=2> 2
<P>
<INPUT type=Button Value="Push to test..."
onClick="sortBy( getRadioValue( this.form.which ) );">
</FORM>

</BODY></HTML>



Other feedback on 'irt.org FAQ Knowledge Base Q341' - show all

©2018 Martin Webb