Concatenating Arrays

suggest change

Two Arrays

var array1 = [1, 2];
var array2 = [3, 4, 5];
var array3 = array1.concat(array2);  // returns a new array
var array3 = [...array1, ...array2]

Results in a new Array:

[1, 2, 3, 4, 5]

Multiple Arrays

var array1 = ["a", "b"],
    array2 = ["c", "d"],
    array3 = ["e", "f"],
    array4 = ["g", "h"];

Provide more Array arguments to array.concat()

var arrConc = array1.concat(array2, array3, array4);

Provide more arguments to []

var arrConc = [...array1, ...array2, ...array3, ...array4]

Results in a new Array:

["a", "b", "c", "d", "e", "f", "g", "h"]

Without Copying the First Array

var longArray = [1, 2, 3, 4, 5, 6, 7, 8],
    shortArray = [9, 10];

Provide the elements of shortArray as parameters to push using Function.prototype.apply

longArray.push.apply(longArray, shortArray);

Use the spread operator to pass the elements of shortArray as separate arguments to push

longArray.push(...shortArray)

The value of longArray is now:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that if the second array is too long (>100,000 entries), you may get a stack overflow error (because of how apply works). To be safe, you can iterate instead:

shortArray.forEach(function (elem) {
    longArray.push(elem);
});

Array and non-array values

var array = ["a", "b"];
var arrConc = array.concat("c", "d");
var arrConc = [...array, "c", "d"]

Results in a new Array:

["a", "b", "c", "d"]

You can also mix arrays with non-arrays

var arr1 = ["a","b"];
var arr2 = ["e", "f"];

var arrConc = arr1.concat("c", "d", arr2);

Results in a new Array:

["a", "b", "c", "d", "e", "f"]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Arrays:
* Syntax
* Concatenating Arrays

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde