Concatenating Arrays
Problem
You want to join two arrays together.
Solution
There are two standard options for concatenating arrays in JavaScript.
The first is to use JavaScript’s Array concat()
method:
Note that array1
is not modified by the operation. The concatenated array is returned as a new object.
If you want to merge two arrays without creating a new object, you can use the following technique:
In the example above, the Array.prototype.push.apply(a, b)
approach modifies array1
in place without creating a new array object.
We can simplify the pattern above using CoffeeScript by creating a new merge()
method for Arrays.
Alternatively, we can pass a CoffeeScript splat (array2...
) directly into push()
, avoiding the Array prototype.
A more idiomatic approach is to use the splat operator (...
) directly in an array literal. This can be used to concatenate any number of arrays.
Discussion
CoffeeScript lacks a special syntax for joining arrays, but concat()
and push()
are standard JavaScript methods.