Skip to content

Instantly share code, notes, and snippets.

@benjamincharity
Created July 27, 2017 18:36
Show Gist options
  • Save benjamincharity/694713dacef41403798907da56eee7f3 to your computer and use it in GitHub Desktop.
Save benjamincharity/694713dacef41403798907da56eee7f3 to your computer and use it in GitHub Desktop.
Order an array of objects by a top-level property value.
/**
* 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