Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a spread element unsuitable for copying multidimensional arrays?

From mdn: Spread Syntax

Note: Typically the spread operators in ES2015 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays. It's the same case with Object.assign() and Object spread syntax. Look at the example below for a better understanding.

var a = [[1], [2], [3]];
var b = [...a];
b.shift().shift(); // 1
// Now array b is: [[2], [3]]

What is the point of the above statement? The above code sample works just the same as if you'd copied the array in a to b using the .slice() method. I tried adding another dimension to the array here: https://repl.it/HKOq/2 and things still worked as expected.

So why is the spread syntax unsuitable for copying multidimensional arrays?

I'd appreciate any help.

EDIT:

Reading the answers by estus and vol7ron helped me figure things out. Basically, as estus points out technically there are just arrays inside arrays rather than multidimensional arrays.

And as vol7ron explains only the first level of the array is copied so the objects in memory remain the same for any further nested elements.

I was also wrong to suspect that using the spread syntax was supposed to behave any differently than the slice operator

like image 970
Gwater17 Avatar asked Dec 03 '22 13:12

Gwater17


1 Answers

Man, programmers are really poor at displaying examples that actually show the difference.

var a = [[['a', 'b'], ['c', 'd']], 'e'];
var b = [...a];
b[0][0][0] = 'z';
b[1] = 'x';
console.log('a', a);
console.log('b', b);

This outputs:

a [[["z", "b"], ["c", "d"]], "e"]
b [[["z", "b"], ["c", "d"]], "x"]

Notice something fishy? Both arrays [0][0][0] value was changed. Meaning that the object sitting at [0][0][0] in both arrays are referenced to the same object, and is not a copy. However the [1] values are different meaning that it is indeed a copy.

Shallow copy means the first level is copied, deeper levels are referenced.

like image 144
basickarl Avatar answered Dec 06 '22 10:12

basickarl