TypeScript Array concat() Method
The TypeScript Array.concat() method merges two or more arrays into a new array. It takes multiple arrays and/or values as parameters and returns a single array containing all the elements. This method helps efficiently combine data from various sources into one array.
Syntax
array.concat(value1, value2, ..., valueN)
Parameter: This method accepts a single parameter multiple times as mentioned above and described below:
- valueN: These parameters are arrays and/or values to concatenate.
Return Value: The method returns a new array containing all elements of the original array followed by the elements of the concatenated arrays and/or values.
The below examples illustrate the Array concat() method in TypeScript.
Example 1: Concatenating Three Arrays of Numbers
The TypeScript code defines three arrays, then concatenates them using the concat() method and logs the result to the console.
const array1: number[] = [11, 12, 13];
const array2: number[] = [14, 15, 16];
const array3: number[] = [17, 18, 19];
const newArray: number[] = array1.concat(array2, array3);
console.log(newArray);
Output:
[ 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
Example 2: Merging Two Arrays of Strings
In TypeScript, define two arrays of strings, then merge them using the concat() method.
const arrayA: string[] = ['a', 'b', 'c'];
const arrayB: string[] = ['d', 'e', 'f'];
const mergedArray: string[] = arrayA.concat(arrayB);
console.log(mergedArray);
Output:
[ 'a', 'b', 'c', 'd', 'e', 'f' ]