TypeScript Array concat()
Syntax & Examples
Array.concat() method
The concat() method in TypeScript is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array containing the values of the joined arrays.
Syntax of Array.concat()
There are 2 variations for the syntax of Array.concat() method. They are:
concat(...items: ConcatArray<T>[]): T[]
Parameters
Parameter | Optional/Required | Description |
---|---|---|
items | optional | Arrays and/or values to concatenate into a new array. |
This method combines multiple arrays or values into a new array.
Returns value of type Array
.
concat(...items: (T | ConcatArray<T>)[]): T[]
Parameters
Parameter | Optional/Required | Description |
---|---|---|
items | optional | Arrays and/or values to concatenate into a new array. |
This method combines multiple arrays or values into a new array.
Returns value of type Array
.
✐ Examples
1 Using concat() method with multiple arrays
In TypeScript, you can use the concat()
method to merge multiple arrays into a new array.
For example,
- Define two arrays
arr1
andarr2
with some initial values. - Use the
concat()
method to mergearr1
andarr2
into a new array. - Store the result in the variable
mergedArray
. - Log
mergedArray
to the console using theconsole.log()
method.
TypeScript Program
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = arr1.concat(arr2);
console.log(mergedArray);
Output
[1, 2, 3, 4, 5, 6]
2 Using concat() method with multiple values
In TypeScript, you can use the concat()
method to concatenate multiple values to an array.
For example,
- Define an array
arr
with some initial values. - Use the
concat()
method to concatenate additional values toarr
. - Store the result in the variable
newArray
. - Log
newArray
to the console using theconsole.log()
method.
TypeScript Program
const arr = [1, 2, 3];
const newArray = arr.concat(4, 5, 6);
console.log(newArray);
Output
[1, 2, 3, 4, 5, 6]
3 Using concat() method with arrays and values
In TypeScript, you can use the concat()
method to concatenate arrays and values together.
For example,
- Define two arrays
arr1
andarr2
with some initial values. - Use the
concat()
method to concatenatearr1
,arr2
, and additional values together. - Store the result in the variable
resultArray
. - Log
resultArray
to the console using theconsole.log()
method.
TypeScript Program
const arr1 = [1, 2];
const arr2 = [5, 6];
const resultArray = arr1.concat(3, 4, arr2);
console.log(resultArray);
Output
[1, 2, 3, 4, 5, 6]
Summary
In this TypeScript tutorial, we learned about concat() method of Array: the syntax and few working examples with output and detailed explanation for each example.