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

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: Logo

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

Facebook photo

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

Connecting to %s

Create a website or blog at