DEV Community

Cover image for 2 Uses of concat method when working with arrays in JavaScript
Kritika Pattalam Bharathkumar
Kritika Pattalam Bharathkumar

Posted on • Originally published at

2 Uses of concat method when working with arrays in JavaScript

Let's see two ways in which concat() method can be used while working with arrays in JavaScript.

1) Merging two or more arrays

Let's now see how we can use the concat method to merge two given arrays, array 1 and array 2

const array1 = [1,2,3,4];
const array2 = [5,6,7];
// merge array 1 into array 2 and store it in a new variable 
const newMergedArray = [].concat(array1, array2);
console.log(newMergedArray); // [1, 2, 3, 4, 5, 6, 7]
console.log(array1); // [1, 2, 3, 4]
console.log(array2); // [5,6,7]
Enter fullscreen mode Exit fullscreen mode

const newMergedArray = [].concat(array1, array2);

In the above line [] creates a new array and the concat methods combine both array1, array2. This can also accept more than 2 arrays for concatenation by just adding them one next to the other

const newMergedArray = [].concat(array1, array2, array 3, arrayN);

Another alternative for merging two arrays is below

const newMergedArray = array1.concat(array2, array 3, arrayN);

2) Flatten single level nested arrays

Let's assume there is a nested array as below, and we would want to flatten it in such a way that the output is [1,2,3,4,5,6,7,8], this can be achieved by using concat() method with the help of spread operator.

const array1 = [1,2,[3,4],[5,6], 7, 8];
const flattened = [].concat(...array1);
console.log(flattened); // [1,2,3,4,5,6,7,8]
Enter fullscreen mode Exit fullscreen mode

P.S. The above code flattens just a single-level nested array.


Check out my other blog posts

Follow me on Twitter | LinkedIn for more web development tips.

Top comments (2)

kritikapattalam profile image
Kritika Pattalam Bharathkumar

100% agree with you. Using Array.prototyoe.flat is the most efficient way, but the post was more about what concat is possible of doing.
Thanks for adding this, its helpful for others reading that concat is not the only way to flatten arrays.

ats1999 profile image
Rahul kumar

To merge: [...ar1,...ar2]