DEV Community

Ashutosh Kumar Singh
Ashutosh Kumar Singh

Posted on • Originally published at Medium on

3 Different ways to cOmbine Arrays in Javascript

3 Different ways to combine Arrays in Javascript

Hi everyone this is my second post, and I am very excited, in this post I will talk about different methods of combining two or more arrays. Before We get started, check out my first post on how to create a twitter bot in javascript in a few steps.

Create a simple yet effective Twitter BOt in nOdejs (javascript)

So let’s get started.

I am going to use Visual Studio code editor,

1. Concat()

The most basic way is using the concat method and concating two different arrays

Its very simple, you just have to define two arrays and combine them as shown

Remember the sequence matters

OR

Another way to use concat is by concating two or more arrays in an empty array

2. using … (Spread Operator)(ES6)(shortcut)

Now the second method is like a shortcut, you just have to store the values of two or more arrays in a different array using …(three dots) or spread operator, it is only available in ES6 version only and its very efficient way to combine arrays and is my personal favorite

As you can see, sequence matters here to

3. Merge Arrays with push

You can also use the push method to combine different arrays like as shown

As you can see first declare an empty array and then use push with … and the contents of the arrays will be copied in the desired array.

Remember if,

don't use … (spread operator), then the whole array will be pushed and you will get a nested array called Two-Dimensional Arrays (that is for another day’s discussion, so let’snot get into that)

That’s all thanks for being with me if you think there are any errors or you want to insight some information feel free to comment below


Top comments (0)