Last active
July 4, 2022 02:22
-
-
Save mrandrewmills/c4c14023f933c1463c11853b24d3768e to your computer and use it in GitHub Desktop.
JS to sort an array of structures by one or more properties
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 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') ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.