EN
TypeScript - copy array
0
points
In this article, we would like to show you how to copy an array in TypeScript.
Quick solution:
const array1: number[] = [1, 2, 3, 4];
const array2: number[] = array1.slice();
console.log(array1); // [ 1, 2, 3, 4 ]
console.log(array2); // [ 1, 2, 3, 4 ]
The below assignment doesn't work because you are assigning not the values inside the array but its reference (we don't want this):
const array1: number[] = [1, 2, 3, 4];
const array2: number[] = array1;
array2[3] = 5;
console.log(array1); // [ 1, 2, 3, 5 ]
console.log(array2); // [ 1, 2, 3, 5 ]
Here are some methods on how to create a new copied array:
Array.concat()
- using spread operator '
...
' Array.slice()
Array.from()
1. Array concat()
method
const array1: number[] = [1, 2, 3, 4];
const array2: number[] = [].concat(array1);
array2[3] = 5;
console.log(array1); // [ 1, 2, 3, 4 ]
console.log(array2); // [ 1, 2, 3, 5 ]
2. Spread operator
const array1: number[] = [1, 2, 3, 4];
const array2: number[] = [...array1];
array2[3] = 5;
console.log(array1); // [ 1, 2, 3, 4 ]
console.log(array2); // [ 1, 2, 3, 5 ]
3. Array slice()
const array1: number[] = [1, 2, 3, 4];
const array2: number[] = array1.slice();
array2[3] = 5;
console.log(array1); // [ 1, 2, 3, 4 ]
console.log(array2); // [ 1, 2, 3, 5 ]
4. Array from()
const array1: number[] = [1, 2, 3, 4];
const array2: number[] = Array.from(array1);
array2[3] = 5;
console.log(array1); // [ 1, 2, 3, 4 ]
console.log(array2); // [ 1, 2, 3, 5 ]
5. Array map()
const letters: string[] = ['A', 'B', 'C'];
const copy: string[] = letters.map((x) => x);
console.log(letters); // [ 'A', 'B', 'C' ]
console.log(copy); // [ 'A', 'B', 'C' ]