How to join multiple arrays in TypeScript?


The array stores the elements of the different data types in TypeScript. It is a collection of elements we can use it to store and access data whenever required.

While working with multiple arrays, we need to combine two or more arrays. There are several ways to combine multiple arrays in TypeScript, and we will look through all ways in this TypeScript tutorial. Also, we will discuss when we should use which way is the best at last.

Uing The For Loop to Join The Two Arrays

We can follow the traditional way of using the for-of loop to join the two arrays. We can iterate through the array and push every element to another array to join both.

Syntax

Users can follow the syntax below to use the for-of loop to join two or more arrays in TypeScript.

let array1 = [ ];
let array2 = [ ];
for (let element of array2) {
   array1.push(element);
}

Algorithm

  • Step 1 − Create two or more arrays.

  • Step 2 − Iterate through every element of the second array using the for-of loop.

  • Step 3 − Inside the for-of loop, push every element of the second array to the first array using the push() method.

  • Step 4 − When iteration of the for-of loop completes, the first array contains the elements of both the array.

Example

We have created the two arrays of the numbers in this example. After that, we iterate through array2 using the for-of loop to merge it into array1.

In the output, users can observe that array1 contains a total of 7 elements, four elements of itself, and three elements of array2.

// defining the two array of numbers and initializing them with some number values
let array1: Array<number> = [10, 20, 30, 40];
let array2: Array<number> = [50, 60, 70];

// Iterate through the every element of array2 and push them to array1
for (let element of array2) {
   array1.push(element);
}

console.log("The array1 after joining the array1 and array2 in the array1");
console.log(array1);

On compiling, it will generate the following JavaScript code:

// defining the two array of numbers and initializing them with some number values
var array1 = [10, 20, 30, 40];
var array2 = [50, 60, 70];

// Iterate through the every element of array2 and push them to array1
for (var _i = 0, array2_1 = array2; _i < array2_1.length; _i++) {
   var element = array2_1[_i];
   array1.push(element);
}

console.log("The array1 after joining the array1 and array2 in the array1");
console.log(array1);

Output

The above code will produce the following output −

The array1 after joining the array1 and array2 in the array1
[ 10, 20, 30, 40, 50, 60, 70 ]

Using The Spread Operator to Join The N Arrays

The symbol of the spread operator is three dots(...). In TypeScript, we can use the spread operator to copy all elements of the iterable objects, such as an array, string, etc., in a single shot.

In our case, we will use the spread operator to join the N different arrays.

Syntax

Users can follow the syntax below to join N arrays in single array using the spread operator.

let first = [];
let second = [];
let result = [...first, ...second, ...arrayN];

Example

In this example, we have defined the first and second arrays. Using the spread operator, we defined the result variable to store the resulting array after joining the first and second arrays. We have also joined the first and second arrays multiple times, which shows how to join N same or different arrays.

Also, we joined the third and first arrays without using the extra memory space.

// Creating the two arrays of numbers and booleans respectively
let first: Array<number> = [302, 560, 767, 8];
let second: Array<boolean> = [true, false, true];

// merging first and second array using the spread operator
let result = [...first, ...second];
console.log("After merging the first and second array.");
console.log(result);

// N array merging using spread operator
result = [...first, ...second, ...first];
console.log("After merging the first and second array multiple times.");
console.log(result);

// In place merging, without using extra space
let third: Array<number> = [98, 65, 6, 3];
third = [...third, ...first];
console.log("After merging to first array to third wihtout using extra memory");
console.log(third);

On compiling, it will generate the following JavaScript code −

var __spreadArrays = (this && this.__spreadArrays) || function () {
   for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
   for (var r = Array(s), k = 0, i = 0; i < il; i++)
   for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
   r[k] = a[j];
   return r;
};
// Creating the two arrays of numbers and booleans respectively
var first = [302, 560, 767, 8];
var second = [true, false, true];

// merging first and second array using the spread operator
var result = __spreadArrays(first, second);
console.log("After merging the first and second array.");
console.log(result);

// N array merging using spread operator
result = __spreadArrays(first, second, first);
console.log("After merging the first and second array multiple times.");
console.log(result);

// In place merging, without using extra space
var third = [98, 65, 6, 3];
third = __spreadArrays(third, first);
console.log("After merging to first array to third wihtout using extra memory");
console.log(third);

Output

The above code will produce the following output −

After merging the first and second array.
[ 302, 560, 767, 8, true, false, true ]
After merging the first and second array multiple times.
[ 302, 560, 767, 8, true, false, true, 302, 560, 767, 8 ]
After merging to first array to third wihtout using extra memory
[ 98, 65, 6, 3, 302, 560, 767, 8 ]

Using The Concat() Method to Join The Multiple Arrays

The concat() method is the built-in library to join or merge multiple arrays and is also an efficient way to join them. We can invoke the contact() method by taking the instance of the array as a reference and can pass other arrays as a parameter of the contact method, which needs to be joined.

Syntax

Users can follow the syntax below to join the multiple arrays using the concat() method in TypeScript.

let arr1 = [];
let arr2 = [];
let result = arr1.concat(arr2,...,arrN);

Parameters

  • arr2, arr3, …, arrN − It is a arrays which needs to be merged with the arr1.

Return value

The concat() method returns the new array after merging the arrays passed as a parameter to the reference array. It merges the array in the same order as we pass in the parameter.

Example

In this example, we have created three different arrays named arr1, arr2, and arr3. First, we have joined arr2 and arr3 to arr1. After that, we joined arr3 and arr1 to arr2.

In the output, users can observe the order of the resultant array, which contains the reference array’s elements first, after the other array elements, as we have passed the arrays in the parameter.

// Defining the three arrays containing the values of the different data types
let arr1 = [20, 30, true, "Hello"];
let arr2 = ["Hi", false, Infinity, NaN];
let arr3 = ["T", "u", "T", "o", "r", "i", "a", "l"];

// Merging the arr2, and arr3 to arr1
let result = arr1.concat(arr2, arr3);
console.log("After merging the arr2, and arr3 to arr1. ");
console.log(result);

// changing the order to concat the array
result = arr2.concat(arr3, arr1);
console.log("After merging the arr3, and arr1 to arr2. ");
console.log(result);

On compiling, it will generate the following JavaScript code −

var arr1 = [20, 30, true, "Hello"];
var arr2 = ["Hi", false, Infinity, NaN];
var arr3 = ["T", "u", "T", "o", "r", "i", "a", "l"];
// Merging the arr2, and arr3 to arr1
var result = arr1.concat(arr2, arr3);
console.log("After merging the arr2, and arr3 to arr1. ");
console.log(result);
// changing the order to concat the array
result = arr2.concat(arr3, arr1);
console.log("After merging the arr3, and arr1 to arr2. ");
console.log(result);

Output

The above code will produce the following output −

After merging the arr2, and arr3 to arr1.
[ 
   20,
   30,
   true,
   'Hello',
   'Hi',
   false,
   Infinity,
   NaN,
   'T',
   'u',
   'T',
   'o',
   'r',
   'i',
   'a',
   'l' ]
After merging the arr3, and arr1 to arr2.
   [ 'Hi',
   false,
   Infinity,
   NaN,
   'T',
   'u',
   'T',
   'o',
   'r',
   'i',
   'a',
   'l',
   20,
   30,
   true,
   'Hello' 
]

We have learned three different methods to join two or more arrays. Also, there are other ways to join arrays. For example, we can use the reduce method to join multiple arrays. Also, we can use the spread operator and push method to join the arrays.

The best and most modern approach to join multiple arrays is using the spread operator; with that, we need to write much less code. The concat() method is also efficient. Using the for-of loop in the development is not recommended to merge multiple arrays. We have added that approach to show how the concat() method works internally.

Updated on: 03-Jan-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements