Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise way to initialize empty multidimensional arrays?

Tags:

javascript

I've been trying to find a reasonably concise way to set the dimensions of an empty multidimensional JavaScript array, but with no success so far.

First, I tried to initialize an empty 10x10x10 array using var theArray = new Array(10, 10 10), but instead, it only created a 1-dimensional array with 3 elements.

I've figured out how to initialize an empty 10x10x10 array using nested for-loops, but it's extremely tedious to write the array initializer this way. Initializing multidimensional arrays using nested for-loops can be quite tedious: is there a more concise way to set the dimensions of empty multidimensional arrays in JavaScript (with arbitrarily many dimensions)?

//Initializing an empty 10x10x10 array:
var theArray = new Array();
for(var a = 0; a < 10; a++){
    theArray[a] = new Array();
    for(var b = 0; b < 10; b++){
        theArray[a][b] = new Array();
        for(var c = 0; c < 10; c++){
            theArray[a][b][c] = 10
        }
    }
}

console.log(JSON.stringify(theArray));
like image 749
Anderson Green Avatar asked Jul 21 '13 19:07

Anderson Green


People also ask

How do you handle multidimensional arrays?

Creating Multidimensional Arrays You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

How do you create an empty two-dimensional array in Java?

To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.

How do you declare an empty multidimensional list in Python?

In Python, the empty list is expressed as [] , so writing l = [] would produce the desired result. If you'd prefer, you can create a new instance of the list class and assign it to a variable. This is done by writing something like l = list() , and does the same thing as the first method.


1 Answers

Adapted from this answer:

function createArray(length) {
  var arr = new Array(length || 0),
      i = length;
    
  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while(i--) arr[i] = createArray.apply(this, args);
  }        
  return arr;
 }

Simply call with an argument for the length of each dimension. Usage examples:

  • var multiArray = createArray(10,10,10); Gives a 3-dimensional array of equal length.
  • var weirdArray = createArray(34,6,42,2); Gives a 4-dimensional array of unequal lengths.
like image 146
mor Avatar answered Oct 20 '22 17:10

mor