How can I make a copy of an array without reference?

7

I would like to know how to make a copy of an array without the reference.

Example of what I'd like to do:

var a = [1,2,3,4];
var b = a;

a[0] = 3;
b[0] = "nao me copie!"
console.log(a[0]) //mostrar 3
console.log(b[0]) //mostrar frase nao me copie!

Thank you!

    
asked by anonymous 25.08.2015 / 08:43

3 answers

8

You can use the method slice without pass arguments to a shallow copy ( source ), or something like angular.copy for a deep copy:

var b = a.slice();
// ou
var b = angular.copy(a);

In your example above it makes no difference to use one or the other, but if the array elements were complex objects, the shallow copy would simply copy the references to the elements, while the deep copy would also copy the elements themselves (recursively):

var a = [true, 10, "teste", [1,2,3], { outro:"objeto" }];

var b1 = a.slice();       // cópia rasa
var b2 = angular.copy(a); // cópia profunda

// Modificando "a"
a[0] = false;         // Não afeta b1 nem b2
a[1] = 20;            // Idem
a[2] = "blábláblá";   // Idem
a[3][1] = 20;         // Afeta b1, pois o sub-array modificado é o mesmo
a[4].um = a[4].outro; // Idem, para o objeto referenciado
delete a[4].outro;

// Visualização
document.body.innerHTML += "<pre>a = " + JSON.stringify(a) + "</pre>";
document.body.innerHTML += "<pre>b1 = a.slice() = " + JSON.stringify(b1) + "</pre>";
document.body.innerHTML += "<pre>b2 = angular.copy(a) = " + JSON.stringify(b2) + "</pre>";
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
25.08.2015 / 09:41
6

If the array does not have objects that also require references, or elements of the DOM, ie consisting of primitives * or primitive objects / arrays * you can do deep copy like this:

var b = JSON.parse(JSON.stringify(a));

Your example would work correctly:

var a = [1,2,3,4];
var b = JSON.parse(JSON.stringify(a));

a[0] = 3;
b[0] = "nao me copie!"
console.log(a[0]) // 3
console.log(b[0]) // nao me copie!

Note: * - about typing in JavaScript read here

    
25.08.2015 / 10:10
0

Using ES6:

var a = ["teste", "teste1"];
var b =[... a];

a[0] = "teste3";
b[0] = "teste4";
console.log(a) //mostrar teste3
console.log(b) //mostrar teste4
    
04.07.2018 / 13:12