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'
};
}
}
}