Search code examples
listcoldfusionlucee

trying to remove an item from List


I have a code working good, but i am trying to do an enhancement

https://trycf.com/gist/5fdbccd52121856991e6fe3f82307d34/lucee5?theme=monokai

in the above, i am trying if the deleted item in list is IN, it should also delete the other item starting with I letter

The code is looping for the list elements and doing a match to detect and delete the element

Source

<cfscript>
    i = 'AS,AK,SK,SB,IN,IP';
    Y = 'IN';
local.X = [];
        listEach(I, function(value, index) {
            if (!listFindNoCase(Y, value)) {
                arrayAppend(X, value);
            }
        });
dump(x);
</cfscript>

Solution

  • You can do that by checking before if the list contains your element using listFindNoCase, then using listFilter to filter the items you do not want in your new list, something like this:

    <cfscript>
    originalList = 'AS,AK,SK,SB,IN,IP';
    needle = 'IN,AS';
    newList = originalList;
    listEach(needle, function(needle) {
        if (listFindNoCase(newList, needle)) {
            newList = listFilter(newList, function(value) {
                return lcase(left(value, 1)) != lcase(left(needle, 1));
            });
        }
    });
    dump(newList);
    </cfscript>