The spread operator ...
is useful to create a copy of a one-dimensional array:
javascriptlet siblings = ['Erik', 'Andrea', 'Paula']; let copy = [...siblings]; copy[0] = 'Erik Martín'; console.log(siblings); // ['Erik', 'Andrea', 'Paula'] console.log(copy); // ['Erik Martín', 'Andrea', 'Paula']
But it doesn't work using multidimensional arrays:
javascriptlet siblings = [['Erik', 1990], ['Andrea', 1993], ['Paula', 2005]]; let copy = [...siblings]; copy[0][0] = 'Erik Martín'; console.log(siblings); // [['Erik Martín', 1990], ['Andrea', 1993], ['Paula', 2005]] console.log(copy); // [['Erik Martín', 1990], ['Andrea', 1993], ['Paula', 2005]]
To do a deep copy of an array (if it's multidimensional), you can use a combination of JSON.parse()
and JSON.stringify()
functions:
javascriptlet siblings = [['Erik', 1990], ['Andrea', 1993], ['Paula', 2005]]; let copy = JSON.parse(JSON.stringify(siblings)); copy[0][0] = 'Erik Martín'; console.log(siblings); // [['Erik', 1990], ['Andrea', 1993], ['Paula', 2005]] console.log(copy); // [['Erik Martín', 1990], ['Andrea', 1993], ['Paula', 2005]]
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.