concat method
The concat
method merges
specified arrays into one common
array. The method is applied to
one of the arrays, and the rest
of the arrays to concatenate are
passed in the method parameters. In
this case, the method does not modify
the original array, but returns a
new one.
Syntax
array.concat(another array, and another array, and another...);
Example
Let's merge 3
arrays into one
using the concat
method:
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3 = [5, 6];
let res = arr1.concat(arr2, arr3);
console.log(res);
The code execution result:
[1, 2, 3, 4, 5, 6]
Example
Now let's merge two arrays together:
let arr1 = [1, 2];
let arr2 = [3, 4];
let res = arr1.concat(arr2);
console.log(res);
The code execution result:
[1, 2, 3, 4]
Example
You can pass not only arrays, but also specific values:
let arr1 = [1, 2];
let arr2 = [3, 4];
let res = arr1.concat(arr2, 5, 6);
console.log(res);
The code execution result:
[1, 2, 3, 4, 5, 6]
Example
You can apply the method to an empty array. In this case, all arrays to be concatenated will be passed as method parameters:
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3 = [5, 6];
let res = [].concat(arr1, arr2, arr3);
console.log(res);
The code execution result:
[1, 2, 3, 4, 5, 6]
See also
-
the
join
method
that concatenate an array into a string