Skip to main content

Command Palette

Search for a command to run...

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

Published
2 min read
2 Uses of concat() method when working with arrays in JavaScript
K

I am a Front end developer currently working on React JS, HTML, CSS, Python, Vue JS, Webpack, Babel, AEM etc.

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.

JavaScript

Part 9 of 10

This series talks about Tips & Tricks and simple projects you can build using JavaScript. Click on the articles below to read more.

Up next

Getting Started with JavaScript - Ultimate Free Resources

A list of resources I used to learn JavaScript as a complete beginner