I have been attempting to duplicate a 2D array by value using the slice() method in order to prevent any changes made to the new array from impacting the original. Oddly enough, it seems that this approach is effective with a 1-dimensional array but not with a 2-dimensional one.
Below is the code I've been working on:
var arrayA = new Array(5); // Create a 2D array
for (var i = 0; i < 5; i++) {
arrayA[i] = new Array(5);
}
for (var x = 0; x < 5; x++) { // Populate the original array
for (var i = 0; i < 5; i++) {
arrayA[x][i] = x + i;
}
}
arrayB = arrayA.slice(); // Create a new array (1)
arrayB[0][0] = 10;
var arrayC = arrayA.slice(); // Create another new array (2) to observe changes when using var
arrayC[0][0] = 100; // Modify the first element of the last array
$(document).click(function() {
alert(arrayA[0][0]); // Outputs 100
alert(arrayB[0][0]); // Outputs 100
alert(arrayC[0][0]); // Outputs 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If anyone knows why the slice method doesn't work properly with multi-dimensional arrays and if there is a workaround for this issue, your insights would be greatly appreciated. Thank you!