Languages
[Edit]
EN

JavaScript - copy array

6 points
Created by:
Anisha-Kidd
652

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]

 

Alternative titles

  1. JavaScript - copy an array
  2. JavaScript - different ways to duplicate array
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