How to Combine Arrays in Javascript


Javascript


In this article, we show how to combine arrays together using the concat() method in Javascript.

So if you have 2 or more separate arrays in Javascript and you want to combine them into a single array, you can do this using the concat() method in Javascript.

The concat() method (short for concatenation) will combine arrays together producing a single array that is composed up of all of the elements of the individual, separate arrays.

In the first example below, we keep it simple.

We have 2 separate arrays and we combine together using the concat() method to produce a single array that has all the elements of both arrays.



So, above, we've combined array1 and array2 into a new array, combinedarray, which has all of the elements of array1 and array2.

So, now the array, combinedarray, will have the elements: "Tom", "John", "Jack", and "Harry".

So this is how to concatenate 2 arrays together.

In the next example, we are going to combine 3 arrays together, so you can see how to concatenate multiple arrays rather than just 2.

This is shown in the example below.



So of course this next example looks similar to the previous one, but we now are combining more than 2 arrays.

In the case when you're combining more than 2 arrays, within the concat() method, you add all the arrays separated by commas, which is what is done above.

So now the array, combinedarray, contains array1, array2, and array3. So it will be composed of: "Tom", "John", "Jack", "Harry", "Steve", "Bob".

So this is how to combine arrays together in Javascript using the concat() method.



HTML Comment Box is loading comments...