How to join two or more arrays in TypeScript using concat()
Overview
In TypeScript, we can join two or more arrays using the concat() method. We can join two, three, or more arrays using this method.
Syntax
array1.concat(array2, array3, ... arrayN)
Concatenate two or more arrays in TypeScript
Parameter values
array1, array2, array3, and arrayN: These are the arrays that we want to join together.
Return value
The concat() method returns a new array with all the elements of the joined arrays.
Example
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let developers: string[] = ["Jane", "Onyejiaku"]let numbers: Array<number>;numbers = [12, 34, 5, 0.9]let evenNumbers: Array<number> = [2, 4, 6]let oddNumbers: Array<number> = [1, 3, 5, 7]let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]// join all arrayslet allNumbers = numbers.concat(evenNumbers, oddNumbers)let allStrings = developers.concat(cars)// print concatenated arraysconsole.log(allNumbers)console.log(allStrings)
Explanation
- Lines 2–8: We create several arrays and initialize them.
- Lines 12–13: We join some of the arrays using the
concat()method. - Lines 16–17: We print the concatenated arrays.