Skip to content

Instantly share code, notes, and snippets.

@mrandrewmills
Last active July 4, 2022 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrandrewmills/c4c14023f933c1463c11853b24d3768e to your computer and use it in GitHub Desktop.
Save mrandrewmills/c4c14023f933c1463c11853b24d3768e to your computer and use it in GitHub Desktop.
JS to sort an array of structures by one or more properties
function propComparator(sortBy){
return function(a,b){
let fieldsToSortBy = sortBy.split(",");
for ( x = 0; x < fieldsToSortBy.length; x++ ) {
let results = 0;
// check if we're comparing dates, handle accordingly
// TBD
// check if we're comparing numerics, handle accordingly
if ( !isNaN( a[fieldsToSortBy[x]] ) && !isNaN( b[fieldsToSortBy[x]] ) ){
results = a[fieldsToSortBy[x]] - b[fieldsToSortBy[x]];
} else {
// otherwise we're comparing strings
results = a[fieldsToSortBy[x]].localeCompare( b[fieldsToSortBy[x]] );
}
if ( results != 0 )
return results;
}
// if we go thru all sort criteria w\o a "winner", then we call a tie
return 0;
}
}
// EXAMPLE USAGE: presidents.sort( propComparator('lastName,firstName') );
@mrandrewmills
Copy link
Author

Given this array of structures:

test2 = [ { firstName: "Gerald", lastName: "Ford" }, { firstName: "James", lastName: "Carter" }, { firstName: "Ronald", lastName: "Reagan" }, { firstName: "George", lastName: "Bush" }, { firstName: "William", lastName: "Clinton" }, { firstName: "George", lastName: "Bush" }, { firstName: "Barack", lastName: "Obama" }, { firstName: "Donald", lastName: "Trump" }, { firstName: "Joseph", lastName: "Biden" } ]

You can define the propComparator function, and then leverage it in the following ways:

presidents.sort( propComparator('lastName,firstName'); // sorts array by lastName, then by firstName
presidents.sort( propComparator('firstName,lastName'); // sorts array by firstName, then by lastName

You get the idea. Just remember, the larger the array of structures, and the more criteria by which you sort, the longer the sorting task may take to complete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment