0

So I'm trying to copy an array to another array so that I can make changes to it without changing the original. Normally I would just use Array.prototype.slice() but I'm using a multidimensional array and it doesn't seem to be working. So for example:

   let arrayOne = ["zebra", "elephant", "lion"];
let arrayTwo = arrayOne.slice();

arrayTwo[1] = "whale";
console.log(arrayOne);

should output ["zebra", "elephant", "lion"] as if the original array has remained untouched and it does. At the same time:

        
        let arrayOne = [];
for (let a = 0; a < 4; a += 1) {
  arrayOne.push([]);
  for (let b = 0; b < 4; b += 1) {
    arrayOne[a].push({itemOne: "success"});
  }
}

let arrayTwo = [];
for (let c = 0; c < 4; c += 1) {
  arrayTwo.push([]);
  for (let d = 0; d < 4; d += 1) {
 arrayTwo[c] = arrayOne[c].slice();
  }
}

arrayTwo[3][1].itemOne = "failure";
console.log("It should be a " + arrayOne[0][0].itemOne);
console.log("and it has been a " + arrayOne[3][1].itemOne);

I'm trying to get this to output "and it has been a success" but it reads "failure". Any ideas as to why?

  • it's nothing to do with the slice, it has to do with the object in the array - for comparison, change the first bit of code to `let arrayOne = [{animal: "zebra"}, {animal:"elephant"}, {animal:"lion"}];` - and then `arrayTwo[1].animal = "whale"` – Jaromanda X Mar 26 '18 at 21:55
  • Typical Primitive Type (Value type) v. Reference Type question. see: https://stackoverflow.com/questions/13266616/primitive-value-vs-reference-value – S. Walker Mar 26 '18 at 21:58
  • So is the only solution to copy each element of the object separately? What if each element of the array contained an object in completely different formats? One might be coordinates and an animal name, another might be a player name and score. – skittleswrapper Mar 26 '18 at 23:00

0 Answers0