I’m sure you must have had a scenario where you had to join or merge two different Arrays. Well, let me tell you that its an easy task. However, there are different ways this can be done.
Merging multiple arrays using Array.concat() method.
Please note that the Array here is not the Array object but an Array variable previously declared.
Array.concat() method accepts two or more array to be concatenated or merged and returns the merged array. Let’s take a look at an example:
var arr1 = ['red','green']; var arr2 = ['blue','yellow']; var arr3 = ['brown','black']; //Now let's merge arr1 with the others var newArr = arr1.concat(arr2,arr3); console.log(newArr); //gives ["red", "green", "blue", "yellow", "brown", "black"] console.log(arr1); //gives ["red", "green"]
If you notice we concatenated the 1st array variable (arr1) with the other ones. Yes, that’s how the method works. You need to use the .concat() method on one of the existing Arrays to merge it with other arrays. The original arrays would not get altered. Instead a new array is created and assigned to the variable you declared.
Merging Arrays using the Spread Operator ( … )
The other way and also the modern way to merge two or more arrays would be to use the spread operator (
... ) . Let’s take a look at an example:
const arr1 = ['red','green']; const arr2 = ['blue','yellow']; const arr3 = ['brown','black']; const colors = [...arr1, ...arr2, arr3]; console.log(colors); //['red', 'green', 'blue', 'yellow', 'brown', 'black']
Using Spread operator to merge arrays would not alter the existing arrays but instead it returns a new array in the new
const that we declared.
Merging Arrays using the Array.push() method
You must have used the Array.push() method earlier to push new values into an Array. However, you can use it to push another array into an existing array too with the help of spread operator. Surprised? Well, try it out!
const arr1 = ['red', 'green']; const arr2 = ['blue', 'yellow'] arr1.push(...arr2); //This will update the arr1 to include the values of arr2 also.
Unlike the previous two methods, using a push would just update the first array.
You can use any of the methods above to merge multiple arrays. Hope you found the article to be useful. Do let us know your comments. Also do share it with your friends if you found this article to be useful.
Comments are closed.