Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove duplicate values from a Coldfusion array?

I have a function that receives a string of tags. In order to save the tags individually, the function transforms the string into an array:

this.tags = listToArray(this.tags, ", ");

How do I remove duplicate values in the event that there are any?

like image 741
Mohamad Avatar asked May 26 '11 02:05

Mohamad


People also ask

How can I remove the duplicate items in an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

Which collection is used to remove duplicate values?

As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.

Which function is used to suppress duplicates?

The function UNIQUE returns the unique values contained in a column.


2 Answers

An easy way to remove duplicates from a list is to convert the list to a struct first, and then conver the struct to an array. However if the order of items in the list is important this may not be appropriate as the elements in the struct will be sorted.

If the order of items is important you would need to build the array manually rather than using the listToArray feature.

<!--- CF9 --->
<cfset tags = "apples,oranges,bananas,pears,APPLES" />
<cfset tagArray = arrayNew(1) />

<cfloop list="#tags#" index="tag" delimiters=",">
    <cfif not ArrayFindNoCase(tagArray,tag)>
        <cfset arrayAppend(tagArray, tag) />
    </cfif>
</cfloop>
like image 137
Antony Avatar answered Sep 29 '22 11:09

Antony


I like to use Java for this kind of task:

<cfset tags = "apples,oranges,bananas,pears,apples" />

<cfset tagsArray = createObject("java", "java.util.HashSet").init(ListToArray(tags)).toArray() />

<cfdump var="#tags#" />
<cfdump var="#tagsArray#" />

Only problem is it takes case into account, so thinks "apples" & "APPLES" are different things (which technically yes, depending on your system may well be different). Way round that is to lower case everything in the list first.

like image 34
Jason Haritou Avatar answered Sep 29 '22 11:09

Jason Haritou