How to merge arrays using spread operator in JavaScript?

Have you come across a requirement to merge two or more arrays  into another array? Let us say, you have two arrays as shown below,


const metrocities = ['Delhi', 'Mumbai','Chennai','Bangalore','Hyderabad'];

const smallcities = ['Jamshedpur','Pune','Lucknow','Trivandrum'];


You need to merge them in another array with optional extra elements in the resultant array. JavaScript array spread operator makes it very simple to merge arrays.

You can merge arrays as using the spread operator as shown below,


let cities = [...metrocities,...smallcities,'Udaipur'];
cities.forEach(item=>console.log(item)); 

As output, you should get items from metrocities and smallcities array with an added item Udaipur. Keep in mind that, this approach created shallow copy of arrray in the resultant array.

I hope, you find this JavaScript tips useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s