Lucee / CF - comma separated list

I have a list of elements that are not formatted sequentially, which I need to sort.

item 1, item 3.0 ,item 8 , item 1.0 , item 4, item 5, item 6, item 10 

In principle, some elements may have spaces (somewhat even) before or after the decimal point (,).

I tried to display the list and then sort, but I found that sorting saved spaces so that elements 1 and item 1.0 would not be sorted correctly. I thought I could use listtoarray to remove spaces, but maybe I'm thinking of a different function, or maybe I need to iterate over my list through a loop?

Can someone update my memory for this main task ???

UPDATED Expected Result:

item 1, item 10, item 3.0, item 4, item 5, item 6, ... etc.

+5
source share
3 answers

You can trim the spaces first, and then sort. Try the code below

 <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#"> 

enter image description here

UPDATE

This can be done using listMap as well

 <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> 
+8
source

For the regular expression parameter, you can use the matching pattern \s*,\s* . This pattern reads as a match with any , with 0 or more space characters before and 0 or more space characters after. Then we can use reReplace to replace these matches with , without 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

+3
source

Here's another way using the same basic idea. Scroll through the list of items and crop them, then finally sort them. 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> 
+2
source

Source: https://habr.com/ru/post/1275496/


All Articles