ColdFusion - ListMinus

Article Information

Article Content

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"

Our Mission

At Wildlink, our mission is to deliver the best business solutions we can to enable our clients to gather and unlock the answers in their data.
We are committed to fostering long-term partnerships built on trust, integrity, and a relentless pursuit of innovation.