merge two arrays in typescript

There are two common ways to merge two arrays in TypeScript: using the spread operator or the concat method.

  1. Using the spread operator:
index.ts
const array1: number[] = [1, 2, 3];
const array2: number[] = [4, 5, 6];
const mergedArray: number[] = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
182 chars
5 lines

In this example, we first define two arrays array1 and array2. Then, we merge both arrays by using the spread operator .... Finally, we store the merged array in mergedArray and log it to the console.

  1. Using the concat method:
index.ts
const array1: number[] = [1, 2, 3];
const array2: number[] = [4, 5, 6];
const mergedArray: number[] = array1.concat(array2);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
181 chars
5 lines

In this example, we use the concat method available on arrays to merge the two arrays. The concat method returns a new array that consists of the original array concatenated with the array(s) or value(s) passed as argument(s). The result is then stored in mergedArray and logged to the console.

Both methods are effective in merging two arrays in TypeScript, but the spread operator approach is generally considered more modern and idiomatic.

gistlibby LogSnag