Skip to content

Instantly share code, notes, and snippets.

@mrandrewmills
Created June 29, 2019 20:27
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/a8c34500714f659ed5ea9ffa7d1ecdee to your computer and use it in GitHub Desktop.
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.
function arrangeArrayStructs(arrayToArrange, arrOrder, whichKey){
var results = [];
arrOrder.forEach( function(item){
results.push( arrayToArrange.filter( record => record[whichKey] == item ) );
});
return results;
}
@mrandrewmills
Copy link
Author

mrandrewmills commented Jun 29, 2019

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:

  • requires ES6 for the arrow feature, so no Internet Explorer 11 (sorry, not sorry)
  • second function parameter must be an array, to deal with possibility of names with commas (e.g. "MLK, Jr. Birthday")
  • the values of the key specified in whichKey parameter must be unique (i.e. if there were two Paul's we'd be screwed)
  • does not modify the original array

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