Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array.slice enough to handle a multidimensional Array in JavaScript?

Tags:

javascript

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(); });
like image 718
runners3431 Avatar asked Aug 25 '14 18:08

runners3431


1 Answers

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.

like image 74
Ted Hopp Avatar answered Sep 22 '22 00:09

Ted Hopp