Languages
[Edit]
EN

JavaScript - copy array

3 points
Created by:
Dirask JS Member
3640

In this article, we would like to show you how to copy an array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let array1 = [1, 2, 3, 4, 'xyz'];
let array2 = array1.slice();
array2[3] = 'value';

console.log(array1);  // [1, 2, 3, 4, "xyz"]
console.log(array2);  // [1, 2, 3, "value", "xyz"]

 

Below assignment doesn't work because you are assigning not the values inside the array but its reference (we don't want this):

// ONLINE-RUNNER:browser;

let array1 = [1, 2, 3, 4, 'xyz'];
let array2 = array1;
array2[3] = 'value';

console.log(array1);  // [1, 2, 3, "value", "xyz"]
console.log(array2);  // [1, 2, 3, "value", "xyz"]

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

// ONLINE-RUNNER:browser;

let array1 = [1, 2, 3, 4, 'xyz'];
let array2 = [].concat(array1);
array2[3] = 'value';

console.log(array1);  // [1, 2, 3, 4, "xyz"]
console.log(array2);  // [1, 2, 3, "value", "xyz"]

 2. Spread operator

// ONLINE-RUNNER:browser;

let array1 = [1, 2, 3, 4, 'xyz'];
let array2 = [...array1];
array2[3] = 'value';

console.log(array1);  // [1, 2, 3, 4, "xyz"]
console.log(array2);  // [1, 2, 3, "value", "xyz"]

3. Array slice()

// ONLINE-RUNNER:browser;

let array1 = [1, 2, 3, 4, 'xyz'];
let array2 = array1.slice();
array2[3] = 'value';

console.log(array1);  // [1, 2, 3, 4, "xyz"]
console.log(array2);  // [1, 2, 3, "value", "xyz"]

4. Array from()

// ONLINE-RUNNER:browser;

let array1 = [1, 2, 3, 4, 'xyz'];
let array2 = Array.from(array1);
array2[3] = 'value';

console.log(array1);  // [1, 2, 3, 4, "xyz"]
console.log(array2);  // [1, 2, 3, "value", "xyz"]

5. Array map()

// ONLINE-RUNNER:browser;

let letters = ['A', 'B', 'C'];
let copy = letters.map((x) => x);

console.log(letters);
console.log(copy);
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