Skip to content

Commit aa730dd

Browse files
committed
add Array::push.apply examples to Concatenating Arrays recipe
1 parent 9d40190 commit aa730dd

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

chapters/arrays/concatenating-arrays.md

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,43 @@ You want to join two arrays together.
99

1010
## Solution
1111

12-
Use JavaScript's Array concat() method:
12+
There are two standard options for concatenating arrays in JavaScript.
13+
14+
The first is to use JavaScript's Array `concat()` method:
1315

1416
{% highlight coffeescript %}
15-
ray1 = [1,2,3]
16-
ray2 = [4,5,6]
17-
ray3 = ray1.concat ray2
17+
array1 = [1, 2, 3]
18+
array2 = [4, 5, 6]
19+
array3 = array1.concat array2
1820
# => [1, 2, 3, 4, 5, 6]
1921
{% endhighlight %}
2022

21-
## Discussion
23+
Note that `array1` is _not_ modified by the operation. The concatenated array is returned as a new object.
24+
25+
If you want to merge two arrays without creating a new object, you can use the following technique:
26+
27+
{% highlight coffeescript %}
28+
array1 = [1, 2, 3]
29+
array2 = [4, 5, 6]
30+
Array::push.apply array1, array2
31+
array1
32+
# => [1, 2, 3, 4, 5, 6]
33+
{% endhighlight %}
34+
35+
In the example above, the `Array.prototype.push.apply(a, b)` approach modifies `array1` in place without creating a new array object.
2236

23-
CoffeeScript lacks a special syntax for joining arrays, but concat is a standard JavaScript method.
37+
We can simplify the pattern above using CoffeeScript by creating a new `merge()` method for Arrays.
38+
39+
{% highlight coffeescript %}
40+
Array::merge = (other) -> Array::push.apply @, other
41+
42+
array1 = [1, 2, 3]
43+
array2 = [4, 5, 6]
44+
array1.merge array2
45+
array1
46+
# => [1, 2, 3, 4, 5, 6]
47+
{% endhighlight %}
48+
49+
## Discussion
2450

25-
Note that ray1 is _not_ modified by the operation. The concatenated array is returned as a new object.
51+
CoffeeScript lacks a special syntax for joining arrays, but `concat()` and `push()` are standard JavaScript methods.

0 commit comments

Comments
 (0)