0

I have the following function to rotate a matrix 90deg and this is the code

function rotateMatrix(array) {
    let counter = 0;
    let resultArr = array.slice();
    let i = 0,
        k = 0,
        p = 0;
        j = array.length - 1;
    console.log(array === resultArr); //false


    while (counter <= Math.pow(array.length, 2)) {
        if (i < array.length) {
            resultArr[k][p] = array[i][j];
            i++;
            p++;
        } else {
            j--;
            k++;
            i = 0;
            p = 0;
        }
    }
    return resultArr;
}

Even though I created a copy of the array whenever I try to mutate the resultArr to insert the values for the rotated matrix, both of the arrays (resultArr & array) gets mutated, when I compare (resultArr === array) it gives me false.

As you can see here: Capture of both arrays in the debbuger

Does anyone have an idea why is this happening?

Taro_Naza
  • 1
  • 5
  • 2
    Looks like you have an array of arrays. Making a copy of the source array copies the row references but it is not a *deep* copy. You have to make copies of both dimensions. – Pointy Apr 18 '20 at 12:54
  • @Pointy I'm not sure I understand, can you link me to an article or video that explains how this works in Javascript? Thank you for the response :) – Taro_Naza Apr 18 '20 at 12:57
  • A 2D array in JavaScript is an array with each element being an array. You have to use `.slice()` to copy every element of the outer array so that you have a complete copy of both dimensions. – Pointy Apr 18 '20 at 12:59

2 Answers2

1

If you want to create a brand new two-dimensional array, you can use a code like following:

const array=[[1,2],[3,4]], array2=array.slice().map(el=>el.slice()); console.log(array2==array); // false console.log(array2[0]==array[0]); // false

or

const array=[[1,2],[3,4]], array2=Array.from(array).map(el=>Array.from(el));

Boris
  • 351
  • 1
  • 3
  • 11
0

The array variable is not actually directing to the values stored in it like other numeric or character variables. It stores the base address of the memory location where the array values are stored. So if you make a copy using

var copyArray = actualArray.slice();

a new copy of the actual array is created and stored in an another location of memory. At this time the new array variable points to the base address of copied array in memory. when you perform comparison over arrays like

array1 === array2

the system is not matching the values stored in it, but the base memory address of each array. Two memory location will not have same address at all. so it will give a false.

examples:

1

var ar1 = [];
var ar2 = [];
console.log(ar1 === ar2); // false

2

var ar1 = [];
var ar2 = ar1.slice();
console.log(ar1 === ar2); // false

3

var ar1 = [];
var ar2 = ar1;
console.log(ar1 === ar2); // true

I think you understood why you got the false from the comparison.

Vipin
  • 96
  • 6