javascript append array to array

JavaScript: How to Append Arrays to Arrays

Appending arrays in JavaScript is a common task that can be accomplished in different ways depending on your needs. Here are some methods to append arrays to arrays in JavaScript:

Method 1: Concatenation Operator

The easiest way to append arrays in JavaScript is by using the concatenation operator (+). This operator concatenates two or more arrays and returns a new array without changing the original ones.


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1 + arr2;

console.log(arr3); // Output: "1,2,34,5,6"

In the above example, we have declared two arrays (arr1 and arr2) and concatenated them using the + operator. However, the result is a string that contains all the elements of both arrays separated by commas. If you want to append arrays as arrays rather than strings, you need to use another method.

Method 2: Array.concat() Method

The Array.concat() method is another way to append arrays in JavaScript. This method creates a new array that contains the elements of the original arrays. You can pass one or more arrays as arguments to the concat() method.


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);

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

In the above example, we have declared two arrays (arr1 and arr2) and concatenated them using the concat() method. The result is a new array (arr3) that contains all the elements of both arrays.

Method 3: Spread Operator

The spread operator (...) is a newer feature in JavaScript that makes it easier to append arrays. This operator allows you to spread the elements of an array into another array. You can use the spread operator to append one or more arrays to another array.


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];

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

In the above example, we have declared two arrays (arr1 and arr2) and used the spread operator (...) to append them to a new array (arr3). This method is concise and easy to read.

Conclusion

In conclusion, there are different ways to append arrays to arrays in JavaScript. The concatenation operator (+), Array.concat() method, and spread operator (...) are three popular methods. Depending on your needs, you can choose the method that suits you best.

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