Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
communitycreator

How to join two or more arrays in TypeScript using concat()

Theodore Kelechukwu Onyejiaku

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 TypeScript
let 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 arrays 
let allNumbers = numbers.concat(evenNumbers, oddNumbers)
let allStrings = developers.concat(cars)

// print concatenated arrays
console.log(allNumbers)
console.log(allStrings)
Join two or more arrays in TypeScript

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.

RELATED TAGS

typescript
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring