Created
August 18, 2016 08:16
-
-
Save tomasr8/1437c62d840a9a8cb5b0ba275e51f061 to your computer and use it in GitHub Desktop.
n-dimensional array creation for js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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