Merging two arrays
I've mentioned this before in passing in previous posts, but I've just used it to solve a problem and thought it deserved it's own blog post!
The problem I had was that I had two arrays that I want to merge into one. ColdFusion doesn't have an in-built function for merging arrays so you end up having to loop and append one element at a time, which is frankly rubbish! Here's an example:
<cfset foo = [1,2,3]>
<cfset bar = [4,5,6]>
<cfloop array="#bar#" index="i">
<cfset ArrayAppend( foo, i )>
</cfloop>
As we all know, ColdFusion is built on-top of Java, so we can take advantage of this and use some of the Java methods. In short we can get rid of the loop and just do this instead:
<cfset foo = [1,2,3]>
<cfset bar = [4,5,6]>
<cfset foo.addAll( bar )>
Much nicer!
- Posted in:
- ColdFusion


Comment by brian – June 09, 2010
Comment by John Whish – June 09, 2010
foo = [1,2,3];
bar = [4,5,6];
foo = ListToArray(ListAppend(ArrayToList(foo),ArrayToList(bar)));
Comment by Steve Glachan – June 09, 2010
For this specific case... well, the odds of arrays being re-done to not implement the Collections interface is probably zero. I guess the specific implementation might somehow become unmodifiable under the covers, but I'd doubt that too.
( Info at: java.sun.com/javase/6/docs/api/java/util/Collection.html#addAll(java.util.Collection) )
However, if you're not happy with minute risk that .addAll might go away, why not take a look at Railo, which has had the ArrayMerge CFML function since v1. :)
Comment by Peter Boughton – June 09, 2010
@Peter, what's this "testing" you refer to? :) I agree with you that the small risk, is outweighed by the benefits and Railo is very cool!
Comment by John Whish – June 09, 2010
Comment by brian – June 09, 2010
Comment by Ben Nadel – June 10, 2010