Created
July 27, 2017 18:36
-
-
Save benjamincharity/694713dacef41403798907da56eee7f3 to your computer and use it in GitHub Desktop.
Order an array of objects by a top-level property value.
This file contains hidden or 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
/** | |
* Order an array alphabetically by property | |
* | |
* @param {Array} items The array of objects to sort | |
* @param {String} property The property to sort by | |
* @param {Boolean} isDescending A flag determining if the array should be sorted ascending or | |
* descending | |
* @return {Array} sortedArray The sorted array | |
*/ | |
export default function orderArrayByProperty(items: any[], property: string, isDescending: boolean = true): any[] { | |
return items.sort((a: string, b: string) => { | |
const nonAlphaRegex = /\W+/g; | |
// Check for existence and lowercase | |
const aProp = a[property] ? a[property].toLowerCase().replace(nonAlphaRegex, '') : null; | |
const bProp = b[property] ? b[property].toLowerCase().replace(nonAlphaRegex, '') : null; | |
// Sort ascending or descending | |
const aIsFirstReturn = isDescending ? -1 : 1; | |
const bIsFirstReturn = isDescending ? 1 : -1; | |
if (aProp < bProp) { | |
// Sort ascending | |
return aIsFirstReturn; | |
} else if (aProp > bProp) { | |
// Sort descending | |
return bIsFirstReturn; | |
} else { | |
// Do not sort | |
return 0; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment