I was trying to used Array.prototype.fill method to create a n x n 2D array but the code was buggy and I eventually found out all arrays inside are actually
In your particular case, since Array.prototype.fill() fills with a single value and in JS objects (such as arrays) are reference types you have all indices carry a reference to the first one. In JS creating an ND array may not be as simple as it seems since arrays will be copied by reference. For a general purpose arrayND function you need an array cloning utility function. Let's see;
Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}
var array3D = arrayND(5,5,5,"five");
array3D[0][1][2] = 5;
console.log(array3D);
arrayND function takes indefinite number of arguments. The last one designates the default value to fill our ND array and the preceding arguments are the sizes of each dimension they represent. (first argument is dimension 1, second argument is dimension 2 etc...)