Languages
[Edit]
EN

JavaScript - how to copy an array

3 points
Created by:
Dirask JS Member
3430

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

The assignment does not 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"]
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