Skip to content

Instantly share code, notes, and snippets.

@tomasr8
Created August 18, 2016 08:16
Show Gist options
  • Save tomasr8/1437c62d840a9a8cb5b0ba275e51f061 to your computer and use it in GitHub Desktop.
Save tomasr8/1437c62d840a9a8cb5b0ba275e51f061 to your computer and use it in GitHub Desktop.
n-dimensional array creation for js
function NdArray(...args) { // n-1 args are dimensions, last argument is the fill value
if(args.length === 2) {
return new Array(args[0]).fill(args[1]);
}
let arr = [];
let newArgs = args.slice(1);
for(let i = 0; i < args[0]; i++) {
arr.push(NdArray(...newArgs));
}
return arr;
}
let twoD = NdArray(3, 2, 5);
console.log(twoD); // Array [ Array[2], Array[2], Array[2] ]
console.log(twoD[0]); // Array [ 5, 5 ]
console.log(twoD[1]); // Array [ 5, 5 ]
console.log(twoD[2]); // Array [ 5, 5 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment