How to merge two or more arrays in JavaScript

Last updated on Sep 7, 2020 by Suraj Sharma



In this tutorial, you will learn how you can merge two or more arrays in JavaScript.

I am going to discuss two approaches to concatenate two arrays.


Suppose we have two arrays to merge.


const array1 = ['Apple', 'Banana', 'Cherry'];

const array2 = ['Stawberry', 'Kiwis', 'Blueberry'];


Merge Arrays


1. Using ES6 Array destructuring


Merging two arrays can be done by using ES6 array destructuring, to create a third array.


const array3 = [...array1, ...array2];

console.log(array3); // ["Apple","Banana","Cherry","Stawberry","Kiwis","Blueberry"]

However, some old browsers, still don’t support Array destructing.



2. Using concat() method


Array.concat() method joins the called Array with a new array and returns a new array. It does not change the existing arrays.


const array3 = array1.concat(array2)

console.log(array3); // ["Apple","Banana","Cherry","Stawberry","Kiwis","Blueberry"]

console.log(array1); // ['Apple', 'Banana', 'Cherry']

console.log(array2); // ['Stawberry', 'Kiwis', 'Blueberry']


Both the above approaches can be used for achieving immutability in JavaScript.



Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.