Created
June 29, 2019 20:27
-
-
Save mrandrewmills/a8c34500714f659ed5ea9ffa7d1ecdee to your computer and use it in GitHub Desktop.
Ever needed to arrange an Array of Structs in a specific order which wasn't alphabetical or numerical? (e.g. Federal Holidays, or Beatles) This function can help you with that.
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 arrangeArrayStructs(arrayToArrange, arrOrder, whichKey){ | |
var results = []; | |
arrOrder.forEach( function(item){ | |
results.push( arrayToArrange.filter( record => record[whichKey] == item ) ); | |
}); | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given this:
var Beatles = [ {"firstName":"John","lastName":"Lennon"}, {"firstName":"Paul","lastName":"McCartney"}, {"firstName":"George","lastName":"Harrison"}, {"firstName":"Ringo","lastName":"Starr"} ];
Doing this:
arrangeArrayStructs(Beatles,["Ringo","George","Paul","John"], "firstName");
Will return this:
0: {firstName: "Ringo", lastName: "Starr"} 1: {firstName: "George", lastName: "Harrison"} 2: {firstName: "Paul", lastName: "McCartney"} 3: {firstName: "John", lastName: "Lennon"}
Some caveats: