Skip to content

Instantly share code, notes, and snippets.

@tarlepp
Created March 20, 2014 15:58
Show Gist options
  • Save tarlepp/9667086 to your computer and use it in GitHub Desktop.
Save tarlepp/9667086 to your computer and use it in GitHub Desktop.
// Sort stories by tasks progress
data.stories.data.sort(dynamicSortMultiple("!tasks.progress", "title", "priority"));
function dynamicSort(property) {
return function(obj1, obj2) {
var reverse = (property.indexOf("!") === 0);
if (reverse) {
property.substr(1);
}
if (property.indexOf(".") !== -1) {
var bits = property.split(".");
if (reverse) {
return obj1[bits[0]][bits[1]] < obj2[bits[0]][bits[1]]
? 1 : obj1[bits[0]][bits[1]] > obj2[bits[0]][bits[1]]
? -1 : 0;
} else {
return obj1[bits[0]][bits[1]] > obj2[bits[0]][bits[1]]
? 1 : obj1[bits[0]][bits[1]] < obj2[bits[0]][bits[1]]
? -1 : 0;
}
} else {
if (reverse) {
return obj1[property] < obj2[property]
? 1 : obj1[property] > obj2[property]
? -1 : 0;
} else {
return obj1[property] > obj2[property]
? 1 : obj1[property] < obj2[property]
? -1 : 0;
}
}
}
}
function dynamicSortMultiple() {
/**
* save the arguments object as it will be overwritten note that arguments object
* is an array-like object consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
// try getting a different result from 0 (equal) as long as we have extra properties to compare
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment