36

Is there a built-in way to join two arrays in ColdFusion, similar to JavaScript's array.concat()?

Jeromy French
  • 11,812
  • 19
  • 76
  • 129
Yisroel
  • 8,164
  • 4
  • 26
  • 26

9 Answers9

50

Not really, but guess what, just use Java! :)

<cfset foo = [1,2,3]>
<cfset bar = [4,5,6]>
<cfset foo.addAll( bar )>

reference: Java's Collection Interface API.

source: http://www.aliaspooryorik.com/blog/index.cfm/e/posts.details/post/merging-two-arrays-267

Henry
  • 32,689
  • 19
  • 120
  • 221
  • 2
    Oddly enough, underlying Java methods do not work always as expected. I still haven't figure out exactly when and why. I often use Java methods for removing duplicates, joining and sorting Arrays, I remember sometimes it didn't work depending how you create arrays, which operations you perform before calling Java method etc. So pay attention! – zarko.susnjar Jun 22 '10 at 19:19
  • 1
    @zarko.susnjar - I know this is an old thread, but the reason for the unexpected results with methods like `removeAll`, `retainAll`, etcetera is that the java methods are not as lenient as your typical CF function. They are usually data type sensitive. So `"2"` (string) and `val(2)` (number) are considered different values/elements. Unless you are absolutely certain the data types in both arrays match, you are better of using other methods IMO. – Leigh Aug 25 '12 at 02:19
  • 2
    Of course, if you are not certain about something, always go the safer and proven way. – zarko.susnjar Aug 29 '12 at 14:14
  • 1
    CF10+ user, pls see my other answer. – Henry Apr 25 '14 at 19:09
49

CF10+, use

arrayAppend(array1, array2, true);

https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-a-b/arrayappend.html

Henry
  • 32,689
  • 19
  • 120
  • 221
  • 12
    +1, It is impressive that you remembered this question and came back two years later to improve it. – John Nov 16 '12 at 19:14
8

If you're using Railo, you can use ArrayMerge (E.g. <cfset NewArray=ArrayMerge(FirstArray,SecondArray)>).

Gert Grenander
  • 16,866
  • 6
  • 40
  • 43
  • 2
    I've added to Adobe's ColdFusion Bug Tracker as feature request at http://cfbugs.adobe.com/cfbugreport/flexbugui/cfbugtracker/main.html#bugId=83397 . Vote it up! :) – Henry Jun 21 '10 at 03:10
  • ArrayConcat Vs. ArrayMerge Vs ArrayAppend ? Please discuss here: http://groups.google.com/group/cfml-conventional-wisdom/browse_thread/thread/95a4b511128c37ae – Henry Jun 21 '10 at 18:59
7

Its kinda dumb how coldfusion misses many basic functions that one would expect from a scripting language. Here's one I had to write quickly.

<cffunction name="mergeArrays" returntype="array" >
    <cfargument name="array1" type="array" required="true" >
    <cfargument name="array2" type="array" required="true" >

    <cfset arrayResult = arrayNew(1) >
    <cfloop array="#array1#" index="elem">
        <cfset arrayAppend(arrayResult,elem) >
    </cfloop>

    <cfloop array="#array2#" index="elem">
        <cfset arrayAppend(arrayResult,elem) >
    </cfloop>

    <cfreturn arrayResult>
</cffunction>
noj
  • 139
  • 1
  • 5
1

In CF 10 or Railo 4, you can use the concat() function of the Underscore.cfc library to get a new array that is a concatenation of two other arrays (without modifying the existing arrays). Example cfscript:

newArray = _.concat([1], [2]);

Result:

// newArray == [1, 2]

Using this method to get a new array is a bit cleaner than creating a new array and calling ArrayAppend on it twice.

(Disclaimer: I wrote Underscore.cfc)

Russ
  • 1,931
  • 1
  • 14
  • 15
0

I took this from Ben Nadel and used it to perform encryption and hashing. Worked like a charm!

<cfscript>
    // Note: BinaryDecode/CharsetDecode return java arrays. 
    // Unlike CF arrays, java arrays are immutable, 
    // so the Java addAll(..) method to merge arrays won't work here. 
    // http://stackoverflow.com/a/10760835/104223

    // function to merge immutable arrays the long way
    function mergeArrays( array1, array2 ){
        var i = 0;
        var newArray = [];
        for (i = 1; i <= arrayLen(arguments.array1); i++) {
            arrayAppend(newArray, arguments.array1[i]);
        }
        for (i = 1; i <= arrayLen(arguments.array2); i++) {
            arrayAppend(newArray, arguments.array2[i]);
        }
        return newArray;
    }


    //convert the saltArray string and CustomerID string to UTF-8 byte arrays.
    saltByteArray = charsetDecode(salt, "utf-8");
    CustomerIdByteArray = charsetDecode(CustomerId, "utf-8");

    //create a new byte array consisting of the CustomerId bytes
    //appended with the salt bytes by merging the two binary arrays 
    //via custom function, mergeArrays
    mergedBytes = mergeArrays( CustomerIdByteArray, saltByteArray );
</cfscript>
Leigh
  • 28,765
  • 10
  • 55
  • 103
Faith Sloan
  • 23
  • 1
  • 8
  • Actually I think you got it from me, haha .. and looking at this thread, *I* probably got it from @noj's answer and rewrote it in cfscript ;) – Leigh Dec 06 '12 at 22:14
0

You can easily concatenate two lists like this:

<cfset combolist = ListAppend(lista,listb, ",")>

So, first convert your two arrays to lists using ArrayToList(). Combine the two lists with the ListAppend() and then convert the answer back to an array with ListToArray().

I don't know how efficient this is, but the code is very simple. I'd love to use the arrayAppend() but I'm in ColdFusion 8.

Leigh
  • 28,765
  • 10
  • 55
  • 103
Betty Mock
  • 1,373
  • 11
  • 23
  • Just keep in mind it is not a complete equivalent as it will a) drop any empty array elements and b) split array values on whatever delimiter is used `,`. ie The single value `arr[1] ="Doe, John"` would become `arr[1] = Doe, arr[2] = John`. – Leigh Mar 12 '13 at 20:21
  • Leigh, you make a good point. This could be worked around by using a different list delimiter, such as ~~~, or ~!~!~! which would not likely appear within the array. – Betty Mock Mar 13 '13 at 22:51
  • True, though multiple characters will not not work in this case. In most versions of CF, multiple characters are treated as separate delimiters. ie `~!` means CF sees the values as delimited by `~` **OR** `!`. (Things may have changed in CF10). Using a single character like ascii 30, and [preserving empty list elements](http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_l_21.html), should get it much closer. – Leigh Mar 14 '13 at 03:47
0

In javascript array.join(s) creates a string out of all of the elements of the array separated by the delimiter s. A similar function to this in ColdFusion is the ArrayToList function. As far as appending an array to another I don't believe there is a CF function for that. Check http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions-pt0_03.html#3473387 to see the list of Array functions in CF. Or try something like this:

<cfscript>
   for(index = 1; index LTE ArrayLen(array2); i = i + 1) {
      ArrayAppend(array1, array2[i]);
  }
</cfscript>
0

Yes, ColdFusion(10+) has an inbuilt function to append two arrays.

Script version : array1.append(array2, true);

Tag version: arrayAppend(array1, array2, true);

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
Chaitu
  • 29
  • 5