I'm using the vanilla JS script list.js and am trying to implement a custom sorting function.
I have been using the sort
method from the List API without issues for normal sorting, however need to create a custom sort for a couple of situations, however because he never provided an example I'm unsure how to do it.
For example I have this code:
var options = {
valueNames: [ 'date', 'amount', 'company', 'name' ]
};
// Instantiate our list
var myList = new List('mylist', options);
// Set our default sort
myList.sort('date', {order: "desc"});
// Control our own sorting via the links
$('a.sort').on('click', function(event) {
// Prevent default action
event.preventDefault();
var element = $(event.target);
// Get sorting method
var method = element.attr('data-sort');
// Work out what way we want to order the results
switch (method) {
case 'date':
case 'amount':
var order = 'desc';
break;
case 'company':
case 'name':
var order = 'asc';
break;
default:
var order = 'desc';
}
// Sort the data
myList.sort(method, {order: order, sortFunction: function(a, b, options){
}});
return false; // IE 8
});
He never stated the expected signature for the function, but I worked out it has 3 parameters filled with data, the first two seem to contain elements from within the sorting list and the third has options of some kind.
I have read about using custom sorting functions but unsure how to complement them here.
One example of a sort we would need is that we have a list of dates, such as:
- 2015 Spring/Summer
- 2014 Spring/Summer
- 2013 Winter
- 2005 Fall
It should sort by highest number first (in this case 2015) then season in this order first to last: winter, fall, spring/summer.
Is it possible to make a custom sort for stuff like that and if so how can it be implemented with this script?
The sorting function should return a negative number if
a
should come beforeb
, 0 if it shouldn't be changed, or a positive number ifb
should come beforea
. Here is one possible implementation, assuming the date is a predictable string with the formatYYYY {{season}}
.You should also validate the date string first, and check if it's a valid season.