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?
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.
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.
The function UNIQUE returns the unique values contained in a column.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With