I have a list of items that are not formatted consistently that I need to sort.
item 1, item 3.0 ,item 8 , item 1.0 , item 4, item 5, item 6, item 10
Basically, some items could have spaces (multiple even) before or after the comma (,).
I attempted to listtoarray and then sort but I found that the sorting retained the spaces in such a way that item 1 and item 1.0 would not be sorted correctly. I thought I could use listtoarray to remove the spaces but maybe I'm thinking of a different function or perhaps I need to loop over my list via a loop?
Can someone refresh my memory on this basic task???
UPDATED Expected result should be:
item 1,item 10,item 3.0,item 4,item 5,item 6,... etc.
You can trim the spaces first and then sort. Try the below code
<cfset listA = "item 1, item 3.0 ,item 8 , item 1.0 , item 4, item 5, item 6, item 10">
<cfset b = arrayMap(listtoarray(listA),function(item,index,arr){return Trim(item)})>
<cfset arraySort(b,"text","asc") >
<cfdump var="#b#">
UPDATE
This can be done using listMap also
<cfscript>
myList="item 1, item 3.0 ,item 8 , item 1.0 , item 4, item 5, item 6, item 10";
myList=ListMap(myList,function(item){return Trim(item);});
myList = listSort(myList, "textnocase", "asc");
writeOutput(myList);
</cfscript>
For a regex option you can use the match pattern \s*,\s*
. This pattern reads as match any ,
with 0 or more whitespace characters before and 0 or more whitespace characters after. Then we can use reReplace
to replace these matches with a ,
with no spaces.
<cfscript>
myList="item 1, item 3.0 ,item 8 , item 1.0 , item 4, item 5, item 6, item 10";
myList = reReplace(trim(myList), "\s*,\s*", ",", "all");
myList = listSort(myList, "textnocase", "asc");
writeOutput(myList);
</cfscript>
TryCF.com example
regex101.com example
Here's another way using the same basic idea. Loop through the list items and trim them, then finally sort. Working example here
<cfscript>
myList = "item 1, item 3.0 ,item 8 , item 1.0 , item 4, item 5, item 6, item 10";
i = 1;
for (item in myList) {
myList = listSetAt(myList, i, trim(item));
i++;
}
myList = listSort(myList, "textnocase", "asc");
writeOutput(myList);
</cfscript>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With