Skip to content

Instantly share code, notes, and snippets.

@tarlepp
Last active August 29, 2015 13:57
Show Gist options
  • Save tarlepp/9667703 to your computer and use it in GitHub Desktop.
Save tarlepp/9667703 to your computer and use it in GitHub Desktop.
// Sort stories by tasks progress, story title and priority
data.stories.data.sort(dynamicSortMultiple("!tasks.progress", "title", "priority"));
function dynamicSort(property) {
return function(obj1, obj2) {
var reverse = (property.indexOf("!") === 0);
var comparisonValue1, comparisonValue2 = '';
if (reverse) {
property = property.substr(1);
}
if (property.indexOf(".") !== -1) {
var bits = property.split(".");
comparisonValue1 = obj1[bits[0]][bits[1]];
comparisonValue2 = obj2[bits[0]][bits[1]];
} else {
comparisonValue1 = obj1[property];
comparisonValue2 = obj2[property];
}
return reverse
? (comparisonValue1 < comparisonValue2 ? 1 : comparisonValue1 > comparisonValue2 ? -1 : 0)
: (comparisonValue1 > comparisonValue2 ? 1 : comparisonValue1 < comparisonValue2 ? -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