Is array.slice enough to clone a multidimensional Array in JavaScript?
For example:
 var array = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]
    ];
 var b = array.slice();
 console.log(b);
I saw a secondary implementation as this from Play by Play: Lea Verou on pluralsight:
 b =  array.slice().map( function(row){ return row.slice(); });
                The docs are pretty clear:
The
slice()method returns a shallow copy of a portion of an array into a new array object.
So the answer is no: slice by itself is not enough to clone a multidimensional array. It will only clone one dimension. You need to recursively clone each element (the way the "secondary implementation" you posted is doing) if you want a deep clone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With