Duplicate the array and manipulate the original

I will begin by apologizing for my poor English. I will try to be as clear as possible. :)

I have a 3-dimensional array (just an array of two-dimensional arrays). My goal is to take one of the two-dimensional arrays and rotate it 90 Β° counterclockwise. It looks like this:

[1|2|3] [4|5|6] [7|8|9] 

I am trying to make it β€œspin” as follows:

 [3|6|9] [2|5|8] [1|4|7] 

I want to change the original array, so I decided that I need to create a copy of it, so I will have a link to work. So here is what I did:

 var temp = []; var cube = [ [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], [ ['B', 'B', 'B'], ['B', 'B', 'B'], ['B', 'B', 'B'] ], [ ['C', 'C', 'C'], ['C', 'C', 'C'], ['C', 'C', 'C'] ], [ ['D', 'D', 'D'], ['D', 'D', 'D'], ['D', 'D', 'D'] ], [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ], [ ['F', 'F', 'F'], ['F', 'F', 'F'], ['F', 'F', 'F'] ] ]; function CCW() { temp = temp.concat(cube[4]); for(var i = 0; i < 3; i++) for(var j = 0; j < 3; j++) cube[4][i][j] = temp[j][2-i]; } CCW(); 

A copy of the source array should be in temp .

Now the problem is in this line: cube[4][i][j] = temp[j][2-i]; . Instead of changing only the array values ​​in cube , it also changes the temp values. I tried changing temp = temp.concat(cube[4]); on temp = cube[4].slice(0); but he made no difference.

How can i fix this? Thank you all.:)

+5
source share
2 answers

when you assign an array directly, this is link assignment in javascript. This means that any changes will be reflected in both. To copy an array, you need to call array.slice ().

Note: it will still be an assignment in a multidimensional array, so you will need to write something recursive to copy an array that has more than one dimension (for any element, for example [1, 2, ['some', 'inner', 'array'], 3])

Does it make clear things?

edit: here is the deepCopyArray function, this should be excluded for any objects, though ...

 function deepCopyArray(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { var a = arr[i], ele; if (a instanceof Array) //current element is an array... ele = deepCopyArray(a); else ele = a; newArr.push(ele); } return newArr; } 
+1
source

var temp = cube.slice ()

Should do the trick, just put it in a for loop for each line.

0
source

Source: https://habr.com/ru/post/1200764/


All Articles