EN
JavaScript - copy array
6
points
In this article, we would like to show you how to copy an array in JavaScript.
Quick solution:
const array = [1, 2, 3];
const copy = array.slice(); // <----- solution
Problem overview
In JavaScript, when the same object is assigned to different variable, reference is used. This way many variables may indicate the same object in the memory. So, making modification on one that varible we see changes on next one. That makes necessary to use some technique to make object copy, what was presented in next sections.
Problem example:
// ONLINE-RUNNER:browser;
const array1 = [1, 2, 3];
const array2 = array1;
array2[1] = 'value';
console.log(array1); // [1, 'value', 3] // array1 variable indicates to the same object like array2 variable
console.log(array2); // [1, 'value', 3]
Possible solutions
1. Array
slice()
method
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
const copy = array.slice(); // <----- solution
console.log(copy); // [1, 2, 3]
2. Spread operator example
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
const copy = [...array]; // <----- solution
console.log(copy); // [1, 2, 3]
3. Array
from()
method
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
const copy = Array.from(array); // <----- solution
console.log(copy); // [1, 2, 3]
4. Array
map()
method
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
const copy = array.map(x => x); // <----- solution
console.log(copy); // [1, 2, 3]
5. Array
concat()
method
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
const copy = [].concat(array); // <----- solution
console.log(copy); // [1, 2, 3]