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 comment

Create a website or blog at WordPress.com