File tree Expand file tree Collapse file tree 1 file changed +33
-7
lines changed Expand file tree Collapse file tree 1 file changed +33
-7
lines changed Original file line number Diff line number Diff line change @@ -9,17 +9,43 @@ You want to join two arrays together.
9
9
10
10
## Solution
11
11
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:
13
15
14
16
{% 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
18
20
# => [ 1, 2, 3, 4, 5, 6]
19
21
{% endhighlight %}
20
22
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.
22
36
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
24
50
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 .
You can’t perform that action at this time.
0 commit comments