Anyone have a function to create 4D arrays (or any number of dimensions for that matter)?
I\'d like to call the function, then after that I can do something like
Here's a simple recursive solution. The real brains is the mdim function. It just calls itself if the depth isn't 1, and when it gets there just returns an empty array.
Since it seems like you might want to use this for a lot of things, I've wrapped it in a prototype off of Array so that you can use it on your arrays automatically (convenience/maintainability tradeoff). If you prefer, grab the mdim function out of the closure and it should work just fine.
There's a simple test case at the end so you can see how to use it. Good luck! :)
//adds a multidimensional array of specified depth to a given array
//I prototyped it off of array for convenience, but you could take
//just the mdim function
Array.prototype.pushDeepArr = function( depth ){
var arr = (mdim = function( depth ){
if( depth-- > 1 ){
return [ mdim( depth ) ];
} else {
return [];
}
})(depth);
this.push(arr);
};
//example: create an array, add two multidimensional arrays
//one of depth 1 and one of depth 5
x = [];
x.pushDeepArr(1);
x.pushDeepArr(5);