How to Add Array to Array in JavaScript

JavaScript arrays are one of the most used data types. They are dynamic, easy to use, and offer a whole bunch of built-in methods we can take advantage of. Adding an array to an existing array is not a complex operation. Let’s see how it is done.

Javascript add array to array

To add an array to an array in JavaScript, use the array.concat() or array.push() method. 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.

array.concat()

To concat or combine two or more arrays, use the concat() method in JavaScript.

Syntax

array1.concat(array2, array3, ..., arrayX)

Arguments

The array2, array3, …, arrayX are required parameters. These are the arrays to be joined.

Example

Let’s create two arrays using square brackets and then 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.

JavaScript Array push()

To add an array to an array, use the array.push() method. The push() method takes an array as an argument, and it returns the added array. The push() method adds a new element at the end of an array. The push() method changes the length of the array and returns the new length.

Syntax

array.push(elem1, elem2, ..., elemX)

Arguments

The array2, array3, …, arrayX are required. The arrays are to be joined.

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' ] ]

Adding array to array at the beginning

To add an array to array at the beginning in JavaScript, use the array.unshift() method. The unshift() is a built-in JavaScript function that adds new elements to the beginning of an array and returns the new length.

Syntax

array.unshift(elem1, elem2, ..., elemX)

Arguments

The elem1, elem2, …, elemX arguments are required. The element(s) to add to the beginning of the array.

Example

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

netflix.unshift(disneyplus)
console.log(netflix)

Output

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

And we added an array at the start of an array.

That’s it for this tutorial.

Leave a Comment