Sorts array elements.
arraySort(array, sortType [, sortOrder [, localeSensitive ]])
or
arraySort(array, callback)
→ returns boolean
someArray.sort(sortType [, sortOrder, localeSensitive ])
numerictexttextnocaseascascdescfunction(element1, element2). Returns whether the first is less than (-1), equal to (0) or greater than (1) the second one (like the compare functions).
falseUses the arraySort() function to get the sorted array and which sorted by type numeric
someArray = [10,20,-99,46,50];
arraySort(someArray, "numeric", "desc");
writeOutput( serializeJSON(someArray) );
Expected Result: [50,46,20,10,-99]
CF 11+ Lucee 4.5+
someArray = ["COLDFUSION","coldfusion","adobe","LucEE","RAILO"];
someArray.sort("text","desc");
writeOutput( serializeJSON(someArray) );
Expected Result: ["coldfusion","adobe","RAILO","LucEE","COLDFUSION"]
Uses the callback function
someArray = [
{name="testemployee", age="32"},
{name="employeetest", age="36"}
];
arraySort(
someArray,
function (e1, e2){
return compare(e1.name, e2.name);
}
);
writeOutput( serializeJSON(someArray) );
Expected Result: [{"NAME":"employeetest","AGE":"36"},{"NAME":"testemployee","AGE":"32"}]
Takes an array of structs and sorts by multiple different keys, similar to the way a query allows.
arrayOfStructs = [
{
"userId": 1,
"firstName": "John",
"lastName": "Doe",
"departmentName": "Sales",
"active": 1
},
{
"userId": 2,
"firstName": "Jane",
"lastName": "Smith",
"departmentName": "Marketing",
"active": 1
},
{
"userId": 3,
"firstName": "Alice",
"lastName": "Johnson",
"departmentName": "Sales",
"active": 0
},
{
"userId": 4,
"firstName": "Bob",
"lastName": "Brown",
"departmentName": "Sales",
"active": 1
},
{
"userId": 5,
"firstName": "Charlie",
"lastName": "Davis",
"departmentName": "Marketing",
"active": 0
}
];
arrayOfStructs.sort((user1,user2) => {
if (user1.active != user2.active) {
return user2.active - user1.active;
}
if (user1.departmentName == user2.departmentName || user1.active == 0) {
if (user1.lastName == user2.lastName) {
return user1.firstName.compare(user2.firstName);
}
return user1.lastName.compare(user2.lastName);
}
return user1.departmentName.compare(user2.departmentName);
});
writeDump(arrayOfStructs);
Expected Result: Sorts by active employees, then by their last name and finally by their first name
Signup for cfbreak to stay updated on the latest news from the ColdFusion / CFML community. One email, every friday.