0

I need to save a copy of a globally set array variable, while I'm modifying it locally. For some reason the code below doesnt seem to do this.

var tileArray;
        .
        .
        .
function simplify (tiles){

    tileArray = tiles;  //tileArray is the global variable passed to simplify()
    for (var i = 0; i < tiles.length; i++){
      if (tiles[i].numeratorDim == ""){tiles[i].numeratorDim = 1};
      if (tiles[i].denominatorDim == ""){tiles[i].denominatorDim = 1};
    };
    while (thereIsAMatch(tiles)){ // a bunch of code modifying tiles, but not tileArray
        for (var i = 0; i < tiles.length; i++){
            for (var j = 0; j < tiles.length; j ++) {
                if (unitsMatch(tiles[i].numeratorUnit, tiles[j].denominatorUnit)) {
                    tiles[i].numeratorDim = parseInt(tiles[i].numeratorDim) - 1; 
                    if (tiles[i].numeratorDim == 0){tiles[i].numeratorUnit = ""}
                        tiles[j].denominatorDim = parseInt(tiles[j].denominatorDim) - 1;
                    if (tiles[j].denominatorDim == 0){tiles[j].denominatorUnit = ""}
                  } // if unitsMatch
              } // for j
          } //for i
        } //while thereIsAMatch
    console.log(tileArray === tiles);  //returns TRUE!! But tileArray hasnt been modified!!

    return tiles;
} // function simplify
Pointy
  • 405,095
  • 59
  • 585
  • 614

3 Answers3

0

You need to do a deep copy on this array because right now tiles and tileArray are pointing to the same piece of memory (reference). You can do this with tileArray = Arrays.from(tiles)

Here's a helpful article: https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a

Michael
  • 49
  • 3
  • `Array.from()` does not disjoin the values, as noted on that link. – Taplar Dec 20 '18 at 22:52
  • 1
    Array.from() did not achieve the deep copy i needed, but you definitely pointed me in the right direction! Thanks! I ended up making new Tile objects in a for loop and populating its methods and properties one-at-a time. (I'm sure there are *way* more elegant ways to do this, but I am just a hobbiest trying to get my program to work, by hook or by crook,) Anyway - really appreciate your willingness to help! – RobertHauss Dec 21 '18 at 15:24
  • Not a problem! :) – Michael Dec 21 '18 at 16:42
-1

Basically, tileArray refers to the same array, instead of creating a copy for that,

Use :

tileArray = tiles.slice()

slice(), operation clones the array and returns the reference

Ankur Goel
  • 311
  • 1
  • 11
-1

Have a look at this question

To clone an array try something like:

var dup_array = original_array.slice();

But note what they say about it being a shallow copy.

Kelvin
  • 333
  • 2
  • 7