How does Array Concatenation Works?
Syntax of concat() method is:
Array.concat(value1, value2, value 3, ……valueN);
Arguments Value1, value2,… are the array or values which are to be combined to given array Returns a new array representing a joined array.
Above is the general way of concatenating the arrays, we also have some other methods to concatenate the arrays,
- Using spread operator E6 (keyboard shortcut): Spread syntax is an ES6 standard which allows elements to be used as arguments, applicable while creating a new array, also known as a destructuring operator.
- Using Push: Using the push() method with spread operator. Let us have a look at some of the examples which will demonstrate the use of concat().
Here array1 and array2 both have 4 elements inside, on concatenation, a new array result is produced.
In the case of more than 2 arrays.
<!DOCTYPE html> <html> <body> <script> var array1=["JS","React","Vue.JS","Ember"]; var array2=["Sai","Karthick","Anu","Lekha"]; var array3=["eduCBa", "w3schools", "udemy", "shaw"]; var array4=["1000","1200","500","null"]; var result=array1.concat(array2, array4, array3); document.write(result); </script> </body> </html>
Here, 4 arrays are combined and the output is as below, Since array4 is combined before array3, data in array4 is displayed first. There is no such thing as arrays should be combined in an order.
We can also combine the elements directly to an array instead of declaring the second array and inserting the array elements.
<!DOCTYPE html> <html> <body> <script> var array1=["JS","React","Vue.JS","Ember"]; var result=array1.concat("1000","1200","500","null"); document.write(result); </script> </body> </html>
<!DOCTYPE html> <html> <body> <script> let array1 = [1, 2, 3, 4, 5, 6] let array2 = [6, 5, 4, 3, 2, 1, 0] let array1_array2 = array1.concat(array2) let array2_array1 = array2.concat(array1) document.write('Combined array1_array2 = '+array1_array2+ '</br>') document.write('Combined array2_array1 = '+array2_array1) </script> </body> </html>
Output always depends on to which array we are combining which array, accordingly data gets inserted into a new array.
We can even combine an array, some elements as below.
<!DOCTYPE html> <html> <body> <script> let array1 = ['A', 'B', 'C', 'D', 'E'] let array2 = ['F', 'G'] let array1_array2 = array1.concat(array2) let array2_array1 = array2.concat(array1, 4, [3, 2] document.write(`Combined array1_array2 = `+array1_array2+ '</br>') document.write(`Combined array2_array1 = `+array2_array1) </script> </body> </html>
With concat(), arrays can also be cloned. We need to create an empty array and concat it with an already existing array.
<!DOCTYPE html> <html> <body> <script> var array1 = ['1','2','3'] var array2 = .concat(array1) document.write(array2) </script> </body> </html>