CFLib.org – Common Function Library Project

ListSortByLen(list[, sortDir][, delimiters])

Last updated July 02, 2002

author

Rob Baxter

Version: 1 | Requires: CF5 | Library: StrLib

Description:
Sorts the elements on a list (either asc or desc, default is "asc") by their Len() value. Uses bubble sort internally and as such is not recommended for large lists.

Return Values:
Returns a string.

Example:

<cfset list = "55555,1,4444,333,7777777,88888888,22,999999999,666666">
<cfoutput>
original list = #list#<br>
Sorted Ascending = #ListSortByLen(list, "asc", ",")#<br>
Sorted Descending = #ListSortByLen(list, "desc", ",")#
</cfoutput>

Parameters:

Name Description Required
list The list to sort. Yes
sortDir Direction of sort. Default is "asc." No
delimiters List delimiter. Default is a comma. No

Full UDF Source:

/**
 * Sorts a list by the length of its elements.
 * 
 * @param list      The list to sort. (Required)
 * @param sortDir      Direction of sort. Default is "asc." (Optional)
 * @param delimiters      List delimiter. Default is a comma. (Optional)
 * @return Returns a string. 
 * @author Rob Baxter (rob@microjuris.com) 
 * @version 1, April 30, 2003 
 */
function ListSortByLen(ListToSort) {
    var SortOrder = "asc";
    var Delimiters = ",";
    var ListIsSorted = "no";
    var ListLen = ListLen(ListToSort, Delimiters);
    var CurListItem = "";
    var NextListItem = "";

    if (ArrayLen(Arguments) gt 1) SortOrder = Arguments[2];
    
    if (ArrayLen(Arguments) gt 2) Delimiters = Arguments[3];
        
    while (Not ListIsSorted) {
        ListIsSorted = "yes";
        for (N = 1; N+1 lte ListLen; N=N+1) {
            CurListItem = ListGetAt(ListToSort, N, Delimiters);
            NextListItem = ListGetAt(ListToSort, N+1, Delimiters);
            
            if( (sortOrder is "asc" and len(curListItem) gt len(nextListItem)) or (sortOrder is "desc" and len(curListItem) lt len(nextListItem))) {
                listToSort = listSetAt(listToSort,n,nextListItem,delimiters);
                listToSort = listSetAt(listToSort,n+1,curListItem,delimiters);
                ListIsSorted = "no";
            }
        }
    }
    return ListToSort;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson