Skip to content Skip to sidebar Skip to footer

Why Can't I Make A Copy Of This 2d Array In Js? How Can I Make A Copy?

I'm implementing a John Conway Game of Life, but I'm having a weird problem. Here is a short version if the code giving me trouble: let lifeMap = [ [true, false, false], [false

Solution 1:

A hat-tip to @Redu's answer which is good for N-dimensional arrays, but in the case of 2D arrays specifically, is unnecessary. In order to deeply clone your particular 2D array, all you need to do is:

let oldLifeMap = lifeMap.map(inner => inner.slice())

This will create a copy of each inner array using .slice() with no arguments, and store it to a copy of the outer array made using .map().

Solution 2:

You may clone an ND (deeply nested) array as follows;

Array.prototype.clone = function(){
  returnthis.map(e =>Array.isArray(e) ? e.clone() : e);
};

or if you don't want to modify Array.prototype you may simply refactor the above code like;

function cloneArray(a){
  return a.map(e => Array.isArray(e) ? cloneArray(e) : e);
};

Post a Comment for "Why Can't I Make A Copy Of This 2d Array In Js? How Can I Make A Copy?"