CFLib.org – Common Function Library Project

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

Last updated July 2, 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;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson