MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript Concatenating Arrays

Two Arrays


var array1 = [1, 2];
var array2 = [3, 4, 5];
var array3 = array1.concat(array2);

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

Output

[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);

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

Output

["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)

Output

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

Array and non-array values

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

Output

["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);

Output

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


Conclusion

In this page (written and validated by ) you learned about Javascript Concatenating Arrays . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Merge two array.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.