Skip to content

Instantly share code, notes, and snippets.

@nashvail
Created June 27, 2015 06:51
Show Gist options
  • Save nashvail/8bb6fa115fd397b2bfa2 to your computer and use it in GitHub Desktop.
Save nashvail/8bb6fa115fd397b2bfa2 to your computer and use it in GitHub Desktop.
JavaScript function to sort an array of objects in descending order by any one of the property present in all of the objects.
/*
* Function : descBy(one of the property name of objects present in an array)
* Usage : arrayHoldingNames.sort(by(firstName));
* ----------------------------------------------------------------------
* Used to sort any array of objects in descending order by a property name
* of the obejcts inside that array.
*/
function descBy(propertyName) {
return function(m, n) {
if(typeof m === 'object' && typeof n === 'object') {
var propertyValueM = m[propertyName];
var propertyValueN = n[propertyName];
if(propertyValueM === propertyValueN) return 0;
if(typeof propetyValueM === typeof propertyVaueN) {
return (propertyValueM < propertyValueN ? 1 : -1);
}else{
return (typeof propertyValueM < propertyValueN ? 1 : -1);
}
}else{
throw {
type : 'Error',
message : 'Expected objects got something else'
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment