2 Uses of concat() method when working with arrays in JavaScript

2 Uses of concat() method when working with arrays in JavaScript

Featured on daily.dev

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]

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]

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

References

Check out my other blog posts

Lets connect on Twitter | LinkedIn for more web development related chats.

Did you find this article valuable?

Support Kritika's Blog by becoming a sponsor. Any amount is appreciated!