Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lucee/CF - Clean up comma delimited list

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.

like image 799
HPWD Avatar asked Feb 22 '18 04:02

HPWD


3 Answers

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

enter image description here

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>
like image 83
Vineesh Avatar answered Nov 07 '22 05:11

Vineesh


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

like image 22
Twillen Avatar answered Nov 07 '22 06:11

Twillen


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>
like image 2
user9263373 Avatar answered Nov 07 '22 06:11

user9263373