Skip to content

Instantly share code, notes, and snippets.

@bradmarshall
Last active November 11, 2016 16:08
Show Gist options
  • Save bradmarshall/6db498c54e09a2c3e1ef2cffb8e56daf to your computer and use it in GitHub Desktop.
Save bradmarshall/6db498c54e09a2c3e1ef2cffb8e56daf to your computer and use it in GitHub Desktop.
Sorting an array of structs in Coldfusion using a "function expression". Function Expressions allow you to pass an anonymous argument to another function. Coldfusion 10 supports function expressions in: arrayEach(), arrayFilter(), arrayFind(), arrayFindAll(), arraySort(), listFilter(), structEach() and structFilter().
<cfscript>
// Testing sorting an array of structs
variables.myArray = [
{
"animal": "cat",
"averageAge": 37
},
{
"animal": "dog",
"averageAge": 32
},
{
"animal": "goldfish",
"averageAge": 2
},
{
"animal": "turkey",
"averageAge": 21
},
{
"animal": "lizard",
"averageAge": 86
},
{
"animal": "polarbear",
"averageAge": 67
}
];
// Outputs unsorted array.
writeDump(variables.myArray);
arraySort(variables.myArray, function(structOne, structTwo) {
if(structOne.animal > structTwo.animal) {
return 1;
} else {
return -1;
}
});
// Array is now sorted! Note that the array is updated in-place (not a copy).
writeDump(variables.myArray);
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment