开发者

coldfusion distinct list

I was wondering if there was an easy way to enforce distinct values i开发者_运维技巧n a coldfusion list or array.

Thanks


<cfset temp = structNew()>
<cfloop list="a,b,c,a,c" index="i">
  <cfset temp[i] = "">
</cfloop>
<cfset distinctList = structKeyList(temp)>

This is the simplest solution I can think of. The cons of this is the order is not preserved, and list items are case insensitive. If you need case insensitivity, use Java's hashset.


Before adding a value check to see if it exists by using arrayContains or listFindNoCase.


There are no predefined functions that do what you are asking for, but it is easy to implement your own functions that would do this. The functions I provided are very simple and easy to expand upon.

variables.myList = "one,two,three";
variables.myList = ListAppendDistinct(variables.myList, "three");
variables.myList = ListAppendDistinct(variables.myList, "four");

function ListAppendDistinct(list, value)
{
    var _local = StructNew();
    _local.list = list;
    if (NOT ListContains(_local.list, value))
    {
        _local.list = ListAppend(_local.list,value);
    }
    return _local.list;
}

You can use the function above to distinctly append to the array, this all assumes you are using default delimiters. I'm not sure of the "size" of your data because it can get expensive.

variables.myArray = ArrayNew(1);
variables.myArray[1] = "one";
variables.myArray[2] = "two";
variables.myArray[3] = "three";

variables.myArray = ArrayAppendDistinct(variables.myArray, "three");
variables.myArray = ArrayAppendDistinct(variables.myArray, "four");

function ArrayAppendDistinct(array, value)
{
    var _local = StructNew();
    _local.list = ArrayToList(array);
    _local.list = ListAppendDistinct(_local.list,value);
    return ListToArray(_local.list);
}


You can use the Underscore.cfc library in CF 10 or Railo 4:

_ = new Underscore();// instantiate the library    
uniqueArray = _.uniq(array);// convert an array to a unique array

I don't think that it gets any simpler than that!

(Disclaimer: I wrote Underscore.cfc)


For those who are looking at this answer now: It is. There is a function called ListRemoveDuplicates(). It was added in ColdFusion 10 (2017).

For example, the code below returns the unique values "AA,BB,CC"

newList = listRemoveDuplicates("AA,BB,CC,AA,AA,AA,BB", ",");
writeOutput("newList = #newList#");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜