To copy an array in TypeScript, you can use similar methods as JavaScript such as spread operator, Array.from(), or Array.slice().
In this example,
array1
with elements.[...array1]
to create a copy of array1
and store it in array2
.const array1: number[] = [1, 2, 3, 4, 5];
const array2: number[] = [...array1];
console.log('Array 1:', array1);
console.log('Array 2 (copy of Array 1):', array2);
Array 1: [ 1, 2, 3, 4, 5 ] Array 2 (copy of Array 1): [ 1, 2, 3, 4, 5 ]
In this example,
array1
with elements.Array.from(array1)
to create a copy of array1
and store it in array2
.Array.from()
creates a new array instance from an array-like or iterable object.const array1: number[] = [1, 2, 3, 4, 5];
const array2: number[] = Array.from(array1);
console.log('Array 1:', array1);
console.log('Array 2 (copy of Array 1):', array2);
Array 1: [ 1, 2, 3, 4, 5 ] Array 2 (copy of Array 1): [ 1, 2, 3, 4, 5 ]
In this example,
array1
with elements.array1.slice()
to create a copy of array1
and store it in array2
.Array.slice()
returns a shallow copy of a portion of an array into a new array object.const array1: number[] = [1, 2, 3, 4, 5];
const array2: number[] = array1.slice();
console.log('Array 1:', array1);
console.log('Array 2 (copy of Array 1):', array2);
Array 1: [ 1, 2, 3, 4, 5 ] Array 2 (copy of Array 1): [ 1, 2, 3, 4, 5 ]
In this tutorial, we learned How to Copy an Array in TypeScript language with well detailed examples.