concat()

The concat() method is used to add the elements listed as the arguments of the concat() method to an existing array. The new items are appended to the end of the array, and the result is returned. It should be noted that the original array is not changed in any way when the new items are added. If within the arguments there is an instance of a different array, the contents of that array are appended to the end of the array the concat() method is being invoked upon.

syntax:

Array.concat(argumentOne, argumentTwo)

arrayName.concat(argumentOne, argumentTwo)

EXAMPLE

arrayOne = new Array(50, 60);

document.write("The contents of the arrayOne array are : " + arrayOne[0] + ", " + arrayOne[1] + ".
")



arrayTwo = new Array(10, 20);

document.write("The contents of the arrayTwo array are : " + arrayTwo[0] + ", " + arrayTwo[1] + ".
")



arrayResult = arrayOne.concat(arrayTwo);

document.write("The contents of the concated arrays within arrayResult are : " + arrayResult[0] + ", " + arrayResult[1] + ", " + arrayResult[2] + ", " + arrayResult[3] )

The exmaple shows the creation of an array, called arrayOne. Within arrayOne are three values, 50, and 60. The document.write statement is used to write some descriptive text as well as the contents of arrayOne to the screen. Next comes the creation of another array, called arrayTwo. Within arrayTwo are three more values, 10, and 20. The document.write statement is used to write some descriptive text as well as the contents of arrayTwo to the screen. The arrayResult is then created which contains the result of the concatenation of arrayOne and arrayTwo. The documnet.write statement following writes the results to the screen, as follows:



The contents of the arrayOne array are : 50, 60.

The contents of the arrayTwo array are : 10, 20.

The contents of the concated arrays within arrayResult are : 50, 60, 10, 20.

It should be noted that in the above example, a new array was created called arrayResult, which was used to hold the new concatenated values of the two arrays. This was not required. If you need to re-use the arrayOne array, you may replace all instances of arrayResult with arrayOne within the above script - the results will be the same, using only two arrays. The contents of arrayTwo will be concatenated to the end of arrayOne instead of creating an entirely new array to hold the data from both arrays.