Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a duplicate of an array and manipulate the original

I will start with an apology about my poor English. I will try to be as clear as I can. :)

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

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

I try to make it "rotate" like this:

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

I want to change the original array, so I figured that I need to create a copy of it so i will have a reference to work with. So, here is what I have done:

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();

The copy of the original 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 values of the array in cube, it changes also the values of temp. I tried to change temp = temp.concat(cube[4]); to temp = cube[4].slice(0); but it did not make any diffrence.

How can I fix that? Thank you all. :)

like image 511
Michael Haddad Avatar asked Nov 11 '22 03:11

Michael Haddad


1 Answers

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

note: this will still be an assignment on a multi-dimensional array, so you will need to write something recursive to copy an array that has more than one dimension (at any element, e.g. [1, 2, ['some', 'inner', 'array'], 3])

does this kind of clear things up?

edit: here's a deepCopyArray function, this needs to be exanded for arbitrary 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;
}
like image 79
kirinthos Avatar answered Nov 14 '22 21:11

kirinthos