In this post, We go over how to merge two arrays in JavaScript using the concat method and the spread syntax.
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' ]
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 !
#javascript #js