May 09, 2021 CoffeeScript
You want to connect two arrays together.
In JavaScript, there are two standard methods for connecting arrays.
The first is to use JavaScript's array method concat():
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array3 = array1.concat array2
# => [1, 2, 3, 4, 5, 6]
It should be noted that array1 has not been modified by the operation. The return value of the new array formed after the connection is a new object.
If you want to connect two arrays without generating new objects, you can use the following techniques:
array1 = [1, 2, 3]
array2 = [4, 5, 6]
Array::push.apply array1, array2
array1
# => [1, 2, 3, 4, 5, 6]
In the example above, the Array.prototype.push.apply(a, b) method modified array1 without producing a new array object.
In CoffeeScript, we can simplify the above approach by creating a new method for arrays.
Array::merge = (other) -> Array::push.apply @, other
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array1.merge array2
array1
# => [1, 2, 3, 4, 5, 6]
Alternatively, I can put a CoffeeScript splat (array2) directly into push(), avoiding the use of array prototypes.
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array1.push array2...
array1
# => [1, 2, 3, 4, 5, 6]
A more language-compliant approach is to use theplat operator (...) directly in an array language. This can be used to connect any number of arrays.
array1 = [1, 2, 3]
array2 = [4, 5, 6]
array3 = [array1..., array2...]
array3
# => [1, 2, 3, 4, 5, 6]
CoffeeScript lacks a special syntax for connecting arrays, but concat() and push() are standard JavaScript methods.