Created
June 27, 2015 06:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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