js combine two arrays

Combining two arrays in JavaScript is a very common task. There are several ways to do this, depending on what you need.


// The most basic way to merge two arrays is to use the concat() method.
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

var arr3 = arr1.concat(arr2);

console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]
        

This method will add the elements of one array to the end of another array, creating a new array. It is important to remember that this method does not mutate the arrays but rather creates a new array which can be stored in a variable like in the above example.


// Another way to merge two arrays is using the spread operator.
var arr4 = [1, 2, 3];
var arr5 = [4, 5, 6];

var arr6 = [...arr4, ...arr5];

console.log(arr6); // Output: [1, 2, 3, 4, 5, 6]
        

The spread operator allows us to expand an array into single elements. This creates a new array which contains all elements from both of the arrays. This method also does not mutate either of the arrays, but rather creates a new array. Finally, you can use the array.push() method. This method will add the elements of one array to the end of another array, mutating the first array. It is important to note that this method will mutate the first array.


// The push() method will mutate the first array.
var arr7 = [1, 2, 3];
var arr8 = [4, 5, 6];

arr7.push(...arr8);

console.log(arr7); // Output: [1, 2, 3, 4, 5, 6]
        

So, depending on your needs, there are several different ways to combine two arrays in JavaScript. Firstly, you can use the concat() method to create a new array which contains all elements from both of the arrays. Secondly, you can use the spread operator to create a new array which contains all elements from both of the arrays. Finally, you can use the array.push() method to add the elements of one array to the end of another array, mutating the first array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe