JavaScript array : How to merge two arrays in JavaScript

JavaScript array : How to merge two arrays in JavaScript

In this post, We go over how to merge two arrays in JavaScript using the concat method and the spread syntax.

Array Concat() method

The concat method is used to merge two arrays. As a result, it returns a new array instead of modifying the existing array.

Let’s look at an example using the concat method. We have two arrays named fruits1 and fruits2. They both contain strings that correspond to a fruit.

const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = fruits1.concat(fruits2);

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]

Array Spread syntax

Now let’s look at an example using the spread syntax.


const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = [...fruits1, ...fruits2];

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]

In this example, we created a new array and assigned it to the variable combinedFruits. We then took the two fruits array and used the spread them out in the array. We used the ... syntax to spread out the contents of the fruits array into the new array.

Thanks for reading !

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

What are the differences between the various JavaScript frameworks? E.g. Vue.js, Angular.js, React.js

What are the differences? Do they each have specific use contexts?

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

In this article we will discuss full details and comparison of both Ember.js and Vue.js