Tutorialspoint.dev

JavaScript | Array concat()

Array.concat() function is used to merge two or more arrays together. This function does not alter the original arrays passed as arguments. The syntax of the function is as follows:

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

Arguments:
The arguments to this function are the arrays or the values that need to be added to the given array. The number of arguments to this function depends upon the number of arrays or values to be merged.

Return value:
This function returns a newly created array that is created after merging all the arrays passed to the function as arguments.

Example 1:

var num1 = [11, 12, 13],
    num2 = [14, 15, 16],
    num3 = [17, 18, 19];
print(num1.concat(num2, num3));

Output:



[11,12,13,14,15,16,17,18,19]

In this example the function concat() concatenates all the three arrays into one array which it return as the answer.

Example 2:

var alpha = ['a', 'b', 'c'];
print(alpha.concat(1, [2, 3]));

Output:

[a,b,c,1,2,3]

In this example the function concat() concatenates all the arguments passed to the function with the given array into one array which it return as the answer.

Example 3:

var num1 = [[23]];
var num2 = [89, [67]];
print(num1.concat(num2));

Output:

[23,89,67] 

In this example the function concat() concatenates both the arrays into one array which it return as the answer.

Codes for the above function are as follows:

Program 1:

<script>
// JavaScript code for concat() function
function func() {
    var num1 = [11, 12, 13],
        num2 = [14, 15, 16],
        num3 = [17, 18, 19];
    document.write(num1.concat(num2, num3));
}
func();
</script>

Output:

[11,12,13,14,15,16,17,18,19]

Program 2:

<script>
// JavaScript code for concat() function
function func() {
    var alpha = ['a', 'b', 'c'];
    document.write(alpha.concat(1, [2, 3]));
}
func();
</script>

Output:

[a,b,c,1,2,3]

Program 3:

<script>
// JavaScript code for concat() function
function func() {
    var num1 = [[23]];
    var num2 = [89, [67]];
    document.write(num1.concat(num2));
}
func();
</script>

Output:

[23,89,67] 


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter