Created
March 10, 2022 02:47
-
-
Save swapnilshrikhande/dd555eecfec5c50b1c5b6ba3b521f768 to your computer and use it in GitHub Desktop.
JavaScript Nested Sort On Multiple Fields
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
var providers = [ | |
{ | |
"provider" : {"name" : "Zaa"}, | |
"licenseStates" : ["TX"] | |
}, | |
{ | |
"provider" : {"name" : "Aaa"}, | |
"licenseStates" : ["CA"] | |
}, | |
{ | |
"provider" : {"name" : "Baa"}, | |
"licenseStates" : ["MA"] | |
}, | |
{ | |
"provider" : {"name" : "Aaa"}, | |
"licenseStates" : ["TX"] | |
}, | |
]; | |
function sortProviders(providers,state){ | |
//based on state set the flag | |
providers = providers.sort((p1, p2) => { | |
return practicesInState(p2,state) - practicesInState(p1,state) | |
|| ('' + p1.provider.name).localeCompare(p2.provider.name); | |
}); | |
return providers; | |
} | |
function practicesInState(p1,state){ | |
if( p1.licenseStates != null | |
&& p1.licenseStates.indexOf(state) != -1 | |
){ | |
return 1; | |
} | |
return -1; | |
} | |
providers = sortProviders(providers,"TX"); | |
console.log("Sorted", JSON.stringify(providers)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment