How to Add Array to Array in JavaScript

To add an array to an array in JavaScript, you can use the “array.concat()” or “array.push()” method.

Method 1: Using the array.concat() function

The array concat() is a built-in method that concatenates two or more arrays. The concat() function does not change the existing arrays but returns a new array containing the values of the joined arrays.

Example

Let’s create two arrays using square brackets and combine them into one array using the concat() method.

const netflix = ["Stranger Things", "Money Heist"]
const disneyplus = ["Loki", "WandaVision"]

const shows = netflix.concat(disneyplus)
console.log(shows)

Output

['Stranger Things', 'Money Heist', 'Loki', 'WandaVision']

And we get the combined array.

Method 2: Using the array push() function

To add an array to an array, you can also use the “array.push()” method. The push() method takes an array as an argument and returns the added array. In addition, it adds a new element at the end of an array.

Example

The array.push() method adds an array as a single element to the existing array. It won’t be flattened.

const netflix = ["Stranger Things", "Money Heist"]
const disneyplus = ["Loki", "WandaVision"]

netflix.push(disneyplus)
console.log(netflix)

Output

[ 'Stranger Things', 'Money Heist', [ 'Loki', 'WandaVision' ] ]

That’s it.

Leave a Comment