Home » How to merge Arrays in TypeScript

How to merge Arrays in TypeScript

Have you ever come across a problem where you would want to merge two array in typescript?

Merge Arrays in TypeScript

Use the spread operator to merge arrays in TypeScript. The spread operator syntax will unpack the values of the arrays into a new array.

The new array will have a type that reflects the types of the values in the supplied arrays.

const array1 = ['abdul', 'daim'];
const array2 = ['.', 'example'];

// 👇️ const concatArray: string[]
// used in typescript
const concatArray = 
[...array1, ...array2];

console.log(concatArray);
/**
result will be 
👉️ ['abdul','daim', '.','example' ]
**/

We used the spread operator to spread the elements of 2 arrays into a third array.

The type of the final array will reflect the type of the provided arrays. This will expand the elements of the first two array and concat the elements into the third array of element

Similarly in typescript the same operator could be used but they will have explicit type such as String. look at this example


const array1 : string[] = ['abdul', 'daim'];
const array2 : string[] = ['.', 'example'];

// 👇️ const concatArray: string[]
// used in typescript
const concatArray: string[] = 
[...array1, ...array2];

console.log(concatArray);
/**
result will be 
👉️ ['abdul','daim', '.','example' ]
**/


assuming if the types get changed the output will be

const array1 : string[] = ['abdul', 'daim'];
const array2 : number[] = [1,2,4,5];

// 👇️ const concatArray: string[]
// used in typescript
const concatArray: (string | number)[] = 
[...array1, ...array2];

console.log(concatArray);
/**
result will be 
👉️ ['abdul','daim', 1,2,4,5 ]
**/


Merge Arrays in TypeScript using concat() function

Alternatively we can also use .concat() function in javascript and typescript. This functions collects the items of two array and merge the items together in one.

Example:



const array1 : string[] = ['abdul', 'daim'];
const array2 : number[] = [1,2,4,5];

// 👇️ const concatArray: string[]
// used in typescript
const concatArray: (string | number)[] = array1.concat(array2)

console.log(concatArray);
/**
result will be 
👉️ ['abdul','daim', 1,2,4,5 ]
**/



More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *