Join items of two arrays into a new array in JavaScript
This post will discuss how to join the items of two arrays into a new array in JavaScript. That is, create a new array that includes all the elements of the first array and then all the elements of the second array, without altering the original arrays.
1. Using Array.concat() function
The standard function to concatenate two or more arrays in JavaScript is Array.concat() function. This function joins two or more arrays and returns a new array that contains all the elements of the original arrays, leaving the original arrays untouched. For example:
|
1 2 3 4 5 |
let first = [1, 2, 3]; let second = [4, 5]; let arr = first.concat(second); console.log(arr); // [1, 2, 3, 4, 5] |
2. Using Spread syntax
Another option is to use the ES6 spread syntax (…) which spreads the array elements into individual values, and can be used to create a new array literal containing the elements of multiple arrays. For example:
|
1 2 3 4 5 |
let first = [1, 2, 3]; let second = [4, 5]; let arr = [...first, ...second]; console.log(arr); // [1, 2, 3, 4, 5] |
3. Using Array.prototype.push() function
The Array.prototype.push() function adds one or more elements to the end of an array and returns the new length of the array. We can use the Function.prototype.apply() function or the spread operator to pass the elements of another array as arguments to the push function. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
let first = [1, 2, 3]; let second = [4, 5]; let arr1 = []; Array.prototype.push.apply(arr1, first); Array.prototype.push.apply(arr1, second); console.log(arr1); // [1, 2, 3, 4, 5] let arr2 = []; arr2.push(...first); arr2.push(...second); console.log(arr2); // [1, 2, 3, 4, 5] |
4. Using Lodash Library
We can also join items of two arrays into a new array using Lodash library. The concat() function of Lodash creates a new array by concatenating an arbitrary number of arrays. It works similarly to the native Array.concat() function, but it also accepts single values as arguments. The following example demonstrates the usage of concat.
|
1 2 3 4 5 6 7 8 9 10 11 |
// import lodash library let _ = require('lodash'); let first = [1, 2, 3]; let second = [4, 5]; let arr1 = _.concat(first, second); console.log(arr1); // [1, 2, 3, 4, 5] let arr2 = _.concat(first, second, 6); console.log(arr2); // [1, 2, 3, 4, 5, 6] |
That’s all about joining the items of two arrays into a new array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)