Remember again, The concat() method does not change the existing arrays, but returns a new array, containing the values of the joined arrays. It is the sign of immutability of objects because you can not merely change anything inside an array. It counts as a pure function, and pure function always returns a new copy of existing array or objects. If you have used Redux previously, then you have known that we used this concat function to return a new state of the class and not modify that state of the class.
array1.concat(array2, array3, ..., arrayX)
Concatenating two arrays
Okay, first, we will test all of our examples in node.js because it is the simplest way and we did not need to write any HTML file to see the output in the console. So it is an easy setup for this example.
Just create one project folder and inside that create one file called concatarray.js and add the following code inside it.
// concatarray.js let realmadrid = ['Gareth Bale', 'Karim Benzema', 'Sergio Ramos']; let barcelona = ['Messi', 'Luis suarez', 'Gerard Pique']; let players = realmadrid.concat(barcelona); console.log(players);
Go to the terminal or cmd and type the following command.
So, here you can see the output like this.
So, it has returned a new array which is the addition of both of the arrays, and now you can check the individual both the arrays and see that none of them are changed. So, it is the pure function that returns a new array without modifying the existing one.
Concat three arrays
We can add more than two arrays. Let us add three arrays.
// concatarray.js let realmadrid = ['Gareth Bale', 'Karim Benzema', 'Sergio Ramos']; let barcelona = ['Messi', 'Luis suarez', 'Gerard Pique']; let chelsea = ['Ngolo Kante', 'Pedro', 'Olivier Geraud'] let players = realmadrid.concat(barcelona, chelsea); console.log(players);
So the concat function takes minimum one argument and maximum as you like.
Concatenating values to an array
Now, let us concat alphanumeric arrays in the following example.
// concatarray.js let realmadrid = ['Gareth Bale', 'Karim Benzema', 'Sergio Ramos']; let alphaNumeric = realmadrid.concat(1, [2, 3], [4,5,6,7,8]); console.log(alphaNumeric);
See in the above example; the first array is the full of strings and second array is integer and array of arrays. Now, look at the output.
So, that means it adds all the items inside one array and then returns it. If the items are the array of arrays then still it will return only one array containing all the items. So the result will not be an array of arrays. It is the single values whether it is integer or string.
Concatenating nested arrays
As I have said earlier if we concat array of arrays then it will return a single array in which not a single element will be an array.
// concatarray.js let numeric = [10, 11, 12, 13]; let arrayNumeric = numeric.concat(1, [2, 3], [4,5,6,7,8]); console.log(arrayNumeric);