about - tech blog -
wildlink.com

Wildlink's Technology Blog
An occasionally updated list of informative articles.
Pulled from our internal wiki.
ColdFusion - ListMinus
2023-06-14

Problem

Sometimes you need to "subtract" a list of values from another list (for example: to detect changes).

Solution

A simple function using ColdFusion's listFilter to test values in the list to see if they exist in the other.

We tried variations of listToArray followed by removeAll, but it would fail in some edge cases, so just do it the "hard" way through listFilter.

listFilter has the advantage that we can also check for negative numerics and remove them (used to filter out "invalid" IDs in the list).

string function listMinus(required string list1, required string list2) {

    var result = listFilter(arguments.list1, function(value) {
        // ignore all negatives
        if (isValid('numeric', value) AND value LE 0) {
            return false;
        }

        // return if NOT in list2
        return NOT listFind(list2, value);
    });
    return result;
}

This is included in our common_utils module available in all 5.5 or newer apps (older apps can find it in the common_utls.cfm file).

Usage

<cfset list1 = "A,b,c,1,-1" />
<cfset list2 = "b,1" />
#listMinus(list1, list2)#

outputs: "A,c"

Back to the Tech Blog
Blog engine: 1.4.0