...

View Full Version : Custom sort



paddymevans
08-25-2010, 03:50 PM
I already have a sort function that but wish to provide my users with the ability to specify custom sorts - days of the week, months etc.

Assuming that I have a function that will return day of week (ie 'Mon' = 0, "Tue" = 1, "Wed" = 2 ... etc) can anyone show me how I would incorporate this into a sort routine?

Many thanks in advance should you respond to this.:thumbsup:

jmrker
08-25-2010, 05:21 PM
I think the function you are looking for is in the Date() object
See: http://www.w3schools.com/jsref/jsref_getDay.asp

In this function, Sun=0, Mon=1, ...Sat=6
but that can still be sorted on.

Old Pedant
08-25-2010, 08:54 PM
Sort *what*???

Sort an array?

Or sort the visible screen contents?

Sorting an array with a custom sort is easy:


var sorted = someArray.sort( nameOfSortFunction );

And your custom sort function is called by Array.sort one pair of elements at a time, with a pair of arguments. Your function should return +1, 0, -1 to indicate whether the first element is larger, the same, or smaller than the second.

Let's take a simple example:


<script type="text/javascript">

function Holiday( when, name )
{
this.eventDate = when;
this.eventName = name;
}

var data = [
new Holiday( new Date( 2010, 9, 12 ), "Columbus Day" ),
new Holiday( new Date( 2010, 8, 6 ), "Labor Day" ),
new Holiday( new Date( 2010, 0, 1 ), "New Years Day" )
];


function compareHolidays( ev1, ev2 )
{
var dt1 = ev1.eventDate.getTime();
var dt2 = ev2.eventDate.getTime();
if ( dt1 < dt2 ) return -1;
if ( dt1 > dt2 ) return 1;
return 0;
}

var sorted = data.sort( compareHolidays );

for ( var i = 0; i < sorted.length; ++i )
{
var ev = sorted[i];
document.write( ev.eventDate.toString() + " :: " + ev.eventName + "<br/>" );
}
</script>


See? Really pretty simple.

Actually, the comparison function can be even simpler:


function compareHolidays( ev1, ev2 )
{
return ev1.eventDate.getTime() - ev2.eventDate.getTime();
}

Actually, instead of -1,0,+1 you can return <0,0,>0 with the same results. So it's pretty flexible.

Naturally, to invert the sort you just reverse the comparison:


function compareHolidays( ev1, ev2 )
{
return ev2.eventDate.getTime() - ev1.eventDate.getTime();
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum