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

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

I am a Front end developer currently working on React JS, HTML, CSS, Python, Vue JS, Webpack, Babel, AEM etc.
No comments yet. Be the first to comment.
This series talks about Tips & Tricks and simple projects you can build using JavaScript. Click on the articles below to read more.
A list of resources I used to learn JavaScript as a complete beginner
Are you planning to start your coding journey?. Then this is for you - a roadmap to help you achieve your goals.

7 ways in which you can add files to your commit using git add

As a website user, one would have come across links or buttons which say "Click to download" or "Download" on a website. Have you ever wondered how can you add one to your website?. Keep reading!!!. As part of this blog let us see how one can crea...

Display Hello World and custom message using two-way data binding

Build a random quote generator using an API - JavaScript

Kritika Pattalam Bharathkumar | Web Developer - The official blog of Kritika Pattalam Bharathkumar
22 posts
Front End Engineer | Writes about HTML, CSS, JavaScript and everything related to web development | Follow me on Twitter let's chat.
Let's see two ways in which concat() method can be used while working with arrays in JavaScript.
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);
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.
Lets connect on Twitter | LinkedIn for more web development related chats.