Skip to main content
deleted 4 characters in body
Source Link
Redu
  • 26.3k
  • 6
  • 61
  • 84

Creating an ND Array requires cloning nested ND arrays. Accordingly you will need a proper Array.prototype.clone() method and the rest is easy. To my knowledge the following is the simplest and most efficient way in JS.

Array.prototype.clone = function(){ return this.reduce((p,c,i) => (p[i] = Array.isArray(c) ? c.clone() : c, p),[]) } function arrayND(...n){ return n.reduceRight((p,c) => c = (new Array(c)).fill(true).map(e => Array.isArray(p) ? p.clone() : p )); } var NDarr = arrayND(4,4,4,4,"."); // size of each dimension and the init value at the end console.log(JSON.stringify(NDarr)) NDarr[0][1][2][3] = "kitty"; //access any location and change. console.log(JSON.stringify(NDarr))

Creating an ND Array requires cloning nested ND arrays. Accordingly you will need a proper Array.prototype.clone() method and the rest is easy. To my knowledge the following is the simplest and most efficient way in JS.

Array.prototype.clone = function(){ return this.reduce((p,c,i) => (p[i] = Array.isArray(c) ? c.clone() : c, p),[]) } function arrayND(...n){ return n.reduceRight((p,c) => c = (new Array(c)).fill(true).map(e => Array.isArray(p) ? p.clone() : p )); } var NDarr = arrayND(4,4,4,4,"."); // size of each dimension and the init value at the end console.log(JSON.stringify(NDarr)) NDarr[0][1][2][3] = "kitty"; //access any location and change. console.log(JSON.stringify(NDarr))

Creating an ND Array requires cloning nested ND arrays. Accordingly you will need a proper Array.prototype.clone() method and the rest is easy. To my knowledge the following is the simplest and most efficient way in JS.

Array.prototype.clone = function(){ return this.reduce((p,c,i) => (p[i] = Array.isArray(c) ? c.clone() : c, p),[]) } function arrayND(...n){ return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p )); } var NDarr = arrayND(4,4,4,4,"."); // size of each dimension and the init value at the end console.log(JSON.stringify(NDarr)) NDarr[0][1][2][3] = "kitty"; //access any location and change. console.log(JSON.stringify(NDarr))

Source Link
Redu
  • 26.3k
  • 6
  • 61
  • 84

Creating an ND Array requires cloning nested ND arrays. Accordingly you will need a proper Array.prototype.clone() method and the rest is easy. To my knowledge the following is the simplest and most efficient way in JS.

Array.prototype.clone = function(){ return this.reduce((p,c,i) => (p[i] = Array.isArray(c) ? c.clone() : c, p),[]) } function arrayND(...n){ return n.reduceRight((p,c) => c = (new Array(c)).fill(true).map(e => Array.isArray(p) ? p.clone() : p )); } var NDarr = arrayND(4,4,4,4,"."); // size of each dimension and the init value at the end console.log(JSON.stringify(NDarr)) NDarr[0][1][2][3] = "kitty"; //access any location and change. console.log(JSON.stringify(NDarr))