Languages
[Edit]
EN

TypeScript - copy array

0 points
Created by:
Vanessa-Drake
718

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' ]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join