How to clone an Array in a new one?

3

I need to pass information from array to another, in short, I want to copy the values of arrayPrimero to arraySegundo , but that the values can be changed without modifying the other, and I do not know how to do, I get error.

Code:

var arrayPrimero=[2,3,4,5]
var arraySegundo=[]
[2, 3, 4, 5] = []

Error:

  

Uncaught SyntaxError: Invalid destructuring assignment target

Is it possible to solve this?

    
asked by rnrneverdies 09.11.2016 в 16:45
source

3 answers

4

Use slice .

var arrayPrimero = [2,3,4,5]
var arraySegundo = arrayPrimero.slice();

arrayPrimero[1] = 123;

console.log(arrayPrimero);
console.log(arraySegundo);

You can also use var arraySegundo= [].concat(arrayPrimero); but it is a slightly less efficient way.

Here I leave a benchmark that shows a comparison of performance between the different ways of cloning an arrangement in javascript (there are several ways) link

Of the native forms, slice is the most performant. But this can now or in the future vary even between browsers.

NOTE: It is worth mentioning that the error you receive is because in javascript (from ECMAScript 2015) there is the deescructurado de arrays which allows you to expand an array in different variables. But this is not related to what you are trying to do but with the syntax that you used.

// se requiere navegador compatible. Probado con Chrome 53
var [uno, dos, tres] = [1,2,3];
console.log(uno,dos,tres);
    
answered by 09.11.2016 / 16:49
source
1

Another option to add the elements of an array to another array can be:

// Variables.
var arrayPrimero = [2,3,4,5];
var arraySegundo = [];

// Recorrer los elementos del arreglo "arrayPrimero"
// para agregarlos al arreglo "arraySegundo".
for (var i = 0; i < arrayPrimero.length; i++) {
   arraySegundo.push(arrayPrimero[i]);
}

// Imprimir los resultados en la consola.
console.log(arraySegundo);
<i>Presiona la tecla F12 y mira la pestaña "Console" de tu navegador para verlos resultados.</i>

To change the value of an element in the array, you can use an example similar to the following:

var nuevo_valor = 10;
var posicion = 1;

// Cambiar el valor que está en la posición "1".
arraySegundo[posicion] = nuevo_valor;
    
answered by 09.11.2016 в 16:50
0

With EcmaScript 2015 (ES6) you can use the spread operator.

const arr = [1, 2, 3];
const copyArr = [...arr];

console.log(copyArr); // [1, 2, 3]
    
answered by 23.05.2018 в 12:23