1381

I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.

  1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)

  2. How would I access its members? (myArray[0][1] or myArray[0,1]?)

royhowie
  • 11,075
  • 14
  • 50
  • 67
Diego
  • 16,830
  • 8
  • 34
  • 46
  • 26
    Assuming a somewhat pedantic definition, it is technically impossible to create a 2d array in javascript. But you can create an array of arrays, which is tantamount to the same. – I. J. Kennedy Jul 29 '14 at 05:05
  • Duplicate of - http://stackoverflow.com/q/6495187/104380 – vsync Mar 26 '16 at 16:55
  • For a 5x3 2D array I would do like `var arr2D = new Array(5).fill(new Array(3));` besides if you don't want the cells to be "undefined" you can do like `var arr2D = new Array(5).fill(new Array(3).fill("hey"));` – Redu May 12 '16 at 16:25
  • 22
    FYI... when you fill an array with more arrays using `var arr2D = new Array(5).fill(new Array(3));`, each element of Array(5) will point to the same Array(3). So it's best to use a for loop to dynamically populate sub arrays. – Josh Stribling May 23 '16 at 08:51
  • 91
    `a = Array(5).fill(0).map(x => Array(10).fill(0))` – Longfei Wu Mar 25 '17 at 14:21
  • @JoshStribling Can you please explain to me why it is that `var arr2D = new Array(5).fill(new Array(3));` doesn't properly create a 2d array? – MarksCode Jun 23 '17 at 17:33
  • @MarksCode It will technically create a 2D array, but it will be an array filled with references to the same single array that you create with the `new Array(3)` call, since that is executed to create a new array, then that array is passed into the function to populate the one that you are filling... – Josh Stribling Sep 16 '17 at 05:37
  • 5
    In other words, `fill` doesn't call `new Array(3)` for each index of the array being filled, since it's not a lambda expression or anything, such as Longfei Wu's comment above, which initially fills the array with 0's, then uses the map function with a lambda to fill each element with a new array. The fill function simply fills the array with exactly what you tell it to. Does that make sense? For more info on the `map` function, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – Josh Stribling Sep 16 '17 at 05:38
  • Possible duplicate of [JavaScript multidimensional array](https://stackoverflow.com/questions/7545641/javascript-multidimensional-array) – Adam Aug 14 '19 at 06:27
  • @Adam this questions seems to be two years older than the question you linked. – kalehmann Aug 14 '19 at 06:46
  • 2
    @kalehmann that is fine: https://meta.stackoverflow.com/a/252017/2311074 `If the new question is a better question or has better answers, then vote to close the old one as a duplicate of the new one.` – Adam Aug 14 '19 at 06:49
  • 1
    A performant one is `let AA = Array.from({ length: 2 }, () => new Array(3).fill(0));` – Manohar Reddy Poreddy Jun 01 '21 at 09:25

55 Answers55

1416

Practically? Yes. You can create an array of arrays which functions as an 2D array as every item is an array itself:

let items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(items[0][0]); // 1
console.log(items[0][1]); // 2
console.log(items[1][0]); // 3
console.log(items[1][1]); // 4
console.log(items);

But technically this is just an array of arrays and not a “true” 2D array, as I. J. Kennedy pointed out.

It should be noted that you could keep nesting arrays into one another and so create “multidimensional” arrays.

A-Tech
  • 806
  • 6
  • 22
Ballsacian1
  • 17,214
  • 2
  • 26
  • 25
  • 44
    It would be difficult to initialize a large multidimensional array this way. However, [this function](http://stackoverflow.com/a/966938/975097) can be used to create an empty multidimensional, with the dimensions specified as parameters. – Anderson Green Apr 06 '13 at 16:49
  • 5
    @AndersonGreen It's a good thing you mentioned a link for those interested in multi-D array solution, but the question and Ballsacian1's answer are about "2D" array, not "multi-D" array – evilReiko Jun 14 '14 at 09:56
  • You should go through the whole thing... e.g. alert(items[0][1]); // 2 etc. – Dois May 28 '15 at 08:11
  • 2
    @SashikaXP, this does not work for first indices other than 0. – Michael Franzl Dec 30 '15 at 17:55
  • 2
    The question is how to declare a two dimensional array. Which is what I was looking for and found this and following answers which fail to discern the difference between declare and initialize. There's also declaration with known length or unbounded, neither of which is discussed. – chris May 30 '16 at 01:20
  • Do you know if we can still use functions like `.lenght` or `.join('')` for example in a multi-dimensionnal array like above or that array is actually considered as an object ? – TOPKAT Jun 13 '16 at 17:07
  • 1
    I believe this is a `jagged array` (array of arrays) - Does JavaScript have a difference between `jagged` and multidimensional as some other languages do? – Luke T O'Brien Sep 03 '16 at 21:11
  • first create 1-D array of row size, then start filling this array using for loop. let matrix = new Array(rowSize); for(let i = 0; i < rows; i++){ matrix[i] = new Array(columnSize); } – Apaar Bhatnagar Jan 01 '19 at 21:35
509

You simply make each item within the array an array.

var x = new Array(10);

for (var i = 0; i < x.length; i++) {
  x[i] = new Array(3);
}

console.log(x);
vsync
  • 118,978
  • 58
  • 307
  • 400
Sufian
  • 8,627
  • 4
  • 22
  • 24
  • 6
    Can they use things like strings for their keys and values? myArray['Book']['item1'] ? – Diego Jun 08 '09 at 19:54
  • 46
    @Diego, yes, but that's not what arrays are intended for. It's better to use an object when your keys are strings. – Matthew Crumley Jun 08 '09 at 20:05
  • 10
    I like this example better than the accepted answer because this can be implemented for dynamically sized arrays, e.g. `new Array(size)` where `size` is a variable. – Variadicism Sep 12 '15 at 22:44
  • 1
    This is working, thanks. You can see the example Gargo https://jsfiddle.net/matasoy/oetw73sj/ – matasoy Sep 23 '16 at 07:23
  • Doesn't work at all!! new Array?? in which language? running the snippet you get only undefined! – Giox May 21 '20 at 22:15
  • @Giox You're probably using ES5 and not running the newest Javascript e.g. ES6. The code works in the console of any modern browser. – xji Aug 19 '20 at 22:17
  • The code works fine; `new Array(3)` creates a new array with 3 indexes, and initializes each to `undefined`. [See 'Array constructor with a single parameter', MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#Array_constructor_with_a_single_parameter). – mgthomas99 Sep 21 '20 at 12:02
225

Similar to activa's answer, here's a function to create an n-dimensional array:

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[length-1 - i] = createArray.apply(this, args);
    }

    return arr;
}

createArray();     // [] or new Array()

createArray(2);    // new Array(2)

createArray(3, 2); // [new Array(2),
                   //  new Array(2),
                   //  new Array(2)]
yckart
  • 32,460
  • 9
  • 122
  • 129
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
  • 2
    Can this create a 4 dimensional array? – trusktr May 19 '11 at 02:18
  • 4
    @trusktr: Yes, you could create as many dimensions as you want (within your memory constraints). Just pass in the length of the four dimensions. For example, `var array = createArray(2, 3, 4, 5);`. – Matthew Crumley May 19 '11 at 04:21
  • Nice! I actually asked about this here: http://stackoverflow.com/questions/6053332/javascript-4d-arrays and a variety of interesting answers. – trusktr May 19 '11 at 05:50
  • 4
    Best answer ! However, I would not recommend to use it with 0 or 1 parameters (useless) – Apolo May 15 '14 at 14:11
  • 1
    n-dimensional you say? Can this create a 5 dimensional array? – BritishDeveloper Jun 19 '15 at 22:19
  • 2
    @BritishDeveloper [Yes.](https://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript/966938#comment7005847_966938) This is a 5D array with each length at 5: `[[[[[null,null],[null,null]],[[null,null],[null,null]]],[[[null,null],[null,null]],[[null,null],[null,null]]]],[[[[null,null],[null,null]],[[null,null],[null,null]]],[[[null,null],[null,null]],[[null,null],[null,null]]]]]` – bb216b3acfd8f72cbc8f899d4d6963 May 20 '19 at 22:25
  • 5
    @haykam sorry to waste your time - I was being sarcastic :/ – BritishDeveloper Jul 18 '19 at 22:39
210

How to create an empty two dimensional array (one-line)

Array.from(Array(2), () => new Array(4))

2 and 4 being first and second dimensions respectively.

We are making use of Array.from, which can take an array-like param and an optional mapping for each of the elements.

Array.from(arrayLike[, mapFn[, thisArg]])

var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);

The same trick can be used to Create a JavaScript array containing 1...N


Alternatively (but more inefficient 12% with n = 10,000)

Array(2).fill(null).map(() => Array(4))

The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map. Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.

var arr = Array(2).fill(null).map(() => Array(4));
arr[0][0] = 'foo';
console.info(arr);

Follow up

Here's a method that appears correct, but has issues.

 Array(2).fill(Array(4)); // BAD! Rows are copied by reference

While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.

var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo';
console.info(arr);
console.info(arr[0][0], arr[1][0]);
Trent
  • 4,208
  • 5
  • 24
  • 46
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • 3
    I suggest this: `Array.from({length:5}, () => [])` – vsync Aug 29 '18 at 09:11
  • 1
    Subjective here but this answer (the first and second within it) seems like the best balance of succinct, fast, and modern. – Brady Dowling Oct 02 '19 at 21:08
  • @zurfyx any idea, or does anyone know, why webstorm is complaining about this? It seems array.from keeps leaving values as undefined and then I can't work with the array created, even though the snippet runs fine here on stackoverflow – FaultyJuggler Nov 09 '19 at 21:29
  • This is by far the best way to create a large, empty multidimensional array in JavaScript – Jessica Aug 19 '20 at 16:43
  • 1
    Best one-liner answer! – Rodrigo Amaral Sep 10 '20 at 13:22
  • 1
    what is the difference between `Array.from(Array(2), () => new Array(4))` and `Array.from(Array(2), () => Array(4))`? – Owen Young May 24 '22 at 07:48
  • @OwenYoung ultimately there is no difference because of the way the constructor for Array was built. *When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.* [see this answer for more details](https://stackoverflow.com/questions/8205691/array-vs-new-array). – Jeremy Iglehart Jun 01 '22 at 16:44
  • There is a mistake here in that `new Array(100).fill(null).map(() => new Array(100).fill(null))` is faster than `Array.from({ length: 100 }, () => Array.from({ length: 100 }, () => null));` When testing arrays of all sizes (10 to 1000), `Array.from` is ~67% slower than `new Array` see: https://jsbench.me/z3l905yt6p/2 – AlexManning Oct 08 '22 at 17:03
98

Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.

The following function can be used to construct a 2-d array of fixed dimensions:

function Create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}

The number of columns is not really important, because it is not required to specify the size of an array before using it.

Then you can just call:

var arr = Create2DArray(100);

arr[50][2] = 5;
arr[70][5] = 7454;
// ...
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
  • i want to make a 2-dim array that would represent a deck of cards. Which would be a 2-dim array that holds the card value and then in then the suit. What would be the easiest way to do that. – Doug Hauf Mar 03 '14 at 17:58
  • 1
    function Create2DArray(rows) { var arr = []; for (var i=0;i – Doug Hauf Mar 03 '14 at 17:58
  • 2
    @Doug: You actually want a one-dimensional array of objects with 2 attributes. var deck= []; deck[0]= { face:1, suit:'H'}; – TeasingDart Sep 18 '15 at 23:21
  • @DougHauf that's a minified 2D-array ?? :P :D – Mahi Nov 09 '16 at 12:50
86

The easiest way:

var myArray = [[]];
Fred
  • 925
  • 6
  • 2
  • 31
    which is a 2-dimension array – Maurizio In denmark Jul 02 '13 at 13:07
  • 17
    Yeah, careful with that. Assigning myArray[0][whatever] is fine, but try and set myArray[1][whatever] and it complains that myArray[1] is undefined. – Philip Apr 17 '14 at 16:24
  • 25
    @Philip you have to set `myArray[1]=[];` before assigning `myArray[1][0]=5;` – 182764125216 Sep 19 '14 at 20:14
  • 1
    Should we use `[[]]` to define that it's a 2-dimensional array? Or simply make it `[]`, and we can use some method like `.push([2,3])`? [DEMO](http://jsbin.com/situyo/edit?js,console,output) – chenghuayang Oct 26 '15 at 13:20
  • Using this syntax, how would you assign it a size? – Aaron Franke Oct 26 '16 at 00:12
  • 7
    Be aware, this does _not_ "create an empty 1x1 array" as @AndersonGreen wrote. It creates a "1x0" array (i.e. 1 row containing an array with 0 columns). `myArray.length == 1` and `myArray[0].length == 0`. Which then gives the wrong result if you then copy a "genuinely empty" "0x0" array into it. – JonBrave Nov 17 '16 at 09:20
  • 4
    @182764125216 that was *knowledge of the day* for me. Thanks :) – th3pirat3 Feb 07 '18 at 23:20
  • This creates only one row with dynamic column. If you want to have multiple rows, you can do something like this: `var myArray= [[], [], [], [], [], []];` This will create 6 rows with each dynamic column. For three dimensional array: `var myArray= [[[], []], [[], []], [[], []]]` This will create _**3x2xdynamicColumn**_ array. – Abdulwehab Aug 10 '22 at 11:52
47

The reason some say that it isn't possible is because a two dimensional array is really just an array of arrays. The other comments here provide perfectly valid methods of creating two dimensional arrays in JavaScript, but the purest point of view would be that you have a one dimensional array of objects, each of those objects would be a one dimensional array consisting of two elements.

So, that's the cause of the conflicting view points.

James Conigliaro
  • 3,809
  • 19
  • 22
  • 43
    No, it's not. In some languages, you can have multidimensional arrays like `string[3,5] = "foo";`. It's a better approach for some scenarios, because the Y axis is not actually a child of the X axis. – rafasoares Aug 04 '11 at 15:29
  • 4
    Once it gets to the underlying machine code, all tensors of dimension > 1 are arrays of arrays, whichever language we are talking about. It is worthwhile keeping this in mind for reasons of cache optimisation. Any decent language that caters seriously for numerical computing will allow you to align your multidimensional structure in memory such that your most-used dimension is stored contiguously. Python's Numpy, Fortran, and C, come to mind. Indeed there are cases when it is worthwhile to reduce dimensionality into multiple structures for this reason. – Thomas Browne Oct 27 '14 at 18:18
  • Computers have no notion of dimensions. There is only 1 dimension, the memory address. Everything else is notational decoration for the benefit of the programmer. – TeasingDart Sep 18 '15 at 23:23
  • 3
    @ThomasBrowne Not exactly. "Arrays of arrays" require some storage for the sizes of inner arrays (they may differ) and another pointer dereferencing to find the place where an inner array is stored. In any "decent" language multidimentional arrays differ from jagged arrays, because they're different data structures per se. (And the confusing part is that C arrays are multidimentional, even though they're indexed with [a][b] syntax.) – polkovnikov.ph Dec 18 '15 at 23:20
39

Few people show the use of push:
To bring something new, I will show you how to initialize the matrix with some value, example: 0 or an empty string "".
Reminding that if you have a 10 elements array, in javascript the last index will be 9!

function matrix( rows, cols, defaultValue){

  var arr = [];

  // Creates all lines:
  for(var i=0; i < rows; i++){

      // Creates an empty line
      arr.push([]);

      // Adds cols to the empty line:
      arr[i].push( new Array(cols));

      for(var j=0; j < cols; j++){
        // Initializes:
        arr[i][j] = defaultValue;
      }
  }

return arr;
}

usage examples:

x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
Sergio Abreu
  • 2,686
  • 25
  • 20
  • I remove last `for` (which sets default value) from your procedure and write `m=matrix(3,4); m[1][2]=2; console.log(JSON.stringify(m));` - and we get very strage matrix (too much nested) - you repair it in last for-defaultValue step, but I think you can rewrite procedure to use less nested arras before setting default values. – Kamil Kiełczewski Jan 21 '20 at 14:42
  • 1
    for javascript world, this is the perfect solutions. Thank you very much for providing this solutions – AMIC MING May 06 '21 at 07:47
  • You are so kind AMIC – Sergio Abreu May 07 '21 at 13:08
30

Two-liner:

var a = []; 
while(a.push([]) < 10);

It will generate an array a of the length 10, filled with arrays. (Push adds an element to an array and returns the new length)

domenukk
  • 953
  • 15
  • 28
28

The sanest answer seems to be

var nrows = ~~(Math.random() * 10);
var ncols = ~~(Math.random() * 10);
console.log(`rows:${nrows}`);
console.log(`cols:${ncols}`);
var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0));
console.log(matrix);

Note we can't directly fill with the rows since fill uses shallow copy constructor, therefore all rows would share the same memory...here is example which demonstrates how each row would be shared (taken from other answers):

// DON'T do this: each row in arr, is shared
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo'; // also modifies arr[1][0]
console.info(arr);
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
Francesco Dondi
  • 1,064
  • 9
  • 17
  • This should be at the very top. I did something similar using `Array.apply(null, Array(nrows))` but this is much more elegant. – dimiguel Mar 25 '16 at 06:05
  • This regard my last comment... Internet Explorer and Opera don't have support for `fill`. This won't work on a majority of browsers. – dimiguel Mar 25 '16 at 20:50
  • @dimgl Fill can be emulated in this instance with a constant map: `Array(nrows).map(() => 0)`, or, `Array(nrows).map(function(){ return 0; });` – Conor O'Brien Jan 17 '17 at 18:56
23

The easiest way:

var arr  = [];

var arr1 = ['00','01'];
var arr2 = ['10','11'];
var arr3 = ['20','21'];

arr.push(arr1);
arr.push(arr2);
arr.push(arr3);

alert(arr[0][1]); // '01'
alert(arr[1][1]); // '11'
alert(arr[2][0]); // '20'
Chicharito
  • 1,450
  • 8
  • 31
  • 49
21

Performance

Today 2020.02.05 I perform tests on MacOs HighSierra 10.13.6 on Chrome v79.0, Safari v13.0.4 and Firefox v72.0, for chosen solutions.

Conclusions for non-initialised 2d array

  • esoteric solution {}/arr[[i,j]] (N) is fastest for big and small arrays and it looks like it is good choice for big sparse arrays
  • solutions based on for-[]/while (A,G) are fast and they are good choice for small arrays.
  • solutions for-[] (B,C) are fast and they are good choice for big arrays
  • solutions based on Array..map/from/fill (I,J,K,L,M) are quite slow for small arrays, and quite fast for big arrays
  • surprinsingly for-Array(n) (B,C) is much slower on safari than for-[] (A)
  • surprinsingly for-[] (A) for big array is slow on all browsers
  • solutions K is slow for small arrays for all browsers
  • solutions A,E,G are slow for big arrays for all browsers
  • solution M is slowest for all arrays on all browsers

enter image description here

Conclusions for initialised 2d array

  • solutions based on for/while (A,B,C,D,E,G) are fastest/quite fast for small arrays on all browsers
  • solutions based on for (A,B,C,E) are fastest/quite fast for big arrays on all browsers
  • solutions based on Array..map/from/fill (I,J,K,L,M) are medium fast or slow for small arrays on all browsers
  • solutions F,G,H,I,J,K,L for big arrays are medium or fast on chrome and safari but slowest on firefox.
  • esoteric solution {}/arr[[i,j]] (N) is slowest for small and big arrays on all browsers

enter image description here

Details

Test for solutions which not fill (initialise) output array

We test speed of solutions for

  • small arrays (12 elements) - you can perform tests on your machine HERE
  • big arrays (1 million elements) arrays - you can perform tests on your machine HERE

function A(r) {
  var arr = [];
  for (var i = 0; i < r; i++) arr[i] = [];
  return arr;
}

function B(r, c) {
  var arr = new Array(r);
  for (var i = 0; i < arr.length; i++) arr[i] = new Array(c);
  return arr;
}

function C(r, c) {
  var arr = Array(r);
  for (var i = 0; i < arr.length; i++) arr[i] = Array(c);
  return arr;
}

function D(r, c) {
  // strange, but works
  var arr = [];
  for (var i = 0; i < r; i++) {
    arr.push([]);
    arr[i].push(Array(c));
  }
  return arr;
}

function E(r, c) {
  let array = [[]];
  for (var x = 0; x < c; x++) {
    array[x] = [];
    for (var y = 0; y < r; y++) array[x][y] = [0];
  }
  return array;
}

function F(r, c) {
  var makeArray = function(dims, arr) {
    if (dims[1] === undefined) {
      return Array(dims[0]);
    }

    arr = Array(dims[0]);

    for (var i = 0; i < dims[0]; i++) {
      arr[i] = Array(dims[1]);
      arr[i] = makeArray(dims.slice(1), arr[i]);
    }

    return arr;
  }
  return makeArray([r, c]);
}

function G(r) {
  var a = [];
  while (a.push([]) < r);
  return a;
}

function H(r,c) {
  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[length-1 - i] = createArray.apply(this, args);
    }

    return arr;
  }
  return createArray(r,c);
}

function I(r, c) {
  return [...Array(r)].map(x => Array(c));
}

function J(r, c) {
  return Array(r).fill(0).map(() => Array(c));
}

function K(r, c) {
  return Array.from(Array(r), () => Array(c));
}

function L(r, c) {
  return Array.from({length: r}).map(e => Array(c));
}

function M(r, c) {
  return Array.from({length: r}, () => Array.from({length: c}, () => {}));
}

function N(r, c) {
  return {}
}



// -----------------------------------------------
// SHOW
// -----------------------------------------------

log = (t, f) => {
  let A = f(3, 4); // create array with 3 rows and 4 columns
  A[1][2] = 6 // 2-nd row 3nd column set to 6
  console.log(`${t}[1][2]: ${A[1][2]}, full: ${JSON.stringify(A).replace(/null/g,'x')}`);
}

log2 = (t, f) => {
  let A = f(3, 4); // create array with 3 rows and 4 columns
  A[[1,2]] = 6 // 2-nd row 3nd column set to 6
  console.log(`${t}[1][2]: ${A[[1,2]]}, full: ${JSON.stringify(A).replace(/null/g,'x')}`);
}

log('A', A);
log('B', B);
log('C', C);
log('D', D);
log('E', E);
log('F', F);
log('G', G);
log('H', H);
log('I', I);
log('J', J);
log('K', K);
log('L', L);
log('M', M);
log2('N', N);
This is presentation of solutions - not benchmark

Test for solutions which fill (initialise) output array

We test speed of solutions for

  • small arrays (12 elements) - you can perform tests on your machine HERE
  • big arrays (1 million elements) arrays - you can perform tests on your machine HERE

function A(r, c, def) {
  var arr = [];
  for (var i = 0; i < r; i++) arr[i] = Array(c).fill(def);
  return arr;
}

function B(r, c, def) {
  var arr = new Array(r);
  for (var i = 0; i < arr.length; i++) arr[i] = new Array(c).fill(def);
  return arr;
}

function C(r, c, def) {
  var arr = Array(r);
  for (var i = 0; i < arr.length; i++) arr[i] = Array(c).fill(def);
  return arr;
}

function D(r, c, def) {
  // strange, but works
  var arr = [];
  for (var i = 0; i < r; i++) {
    arr.push([]);
    arr[i].push(Array(c));
  }
  for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[i][j]=def
  return arr;
}

function E(r, c, def) {
  let array = [[]];
  for (var x = 0; x < c; x++) {
    array[x] = [];
    for (var y = 0; y < r; y++) array[x][y] = def;
  }
  return array;
}

function F(r, c, def) {
  var makeArray = function(dims, arr) {
    if (dims[1] === undefined) {
      return Array(dims[0]).fill(def);
    }

    arr = Array(dims[0]);

    for (var i = 0; i < dims[0]; i++) {
      arr[i] = Array(dims[1]);
      arr[i] = makeArray(dims.slice(1), arr[i]);
    }

    return arr;
  }
  return makeArray([r, c]);
}

function G(r, c, def) {
  var a = [];
  while (a.push(Array(c).fill(def)) < r);
  return a;
}

function H(r,c, def) {
  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[length-1 - i] = createArray.apply(this, args).fill(def);
    }

    return arr;
  }
  return createArray(r,c);
}

function I(r, c, def) {
  return [...Array(r)].map(x => Array(c).fill(def));
}

function J(r, c, def) {
  return Array(r).fill(0).map(() => Array(c).fill(def));
}

function K(r, c, def) {
  return Array.from(Array(r), () => Array(c).fill(def));
}

function L(r, c, def) {
  return Array.from({length: r}).map(e => Array(c).fill(def));
}

function M(r, c, def) {
  return Array.from({length: r}, () => Array.from({length: c}, () => def));
}

function N(r, c, def) {
  let arr={};
  for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[[i,j]]=def;
  return arr;
}



// -----------------------------------------------
// SHOW
// -----------------------------------------------

log = (t, f) => {
  let A = f(1000,1000,7); // create array with 1000 rows and 1000 columns, 
                          // each array cell initilised by 7
  A[800][900] = 5         // 800nd row and 901nd column set to 5
  console.log(`${t}[1][2]: ${A[1][2]}, ${t}[800][901]: ${A[800][900]}`);
}

log2 = (t, f) => {
  let A = f(1000,1000,7); // create array with 1000 rows and 1000 columns, 
                          // each array cell initilised by 7
  A[[800,900]] = 5            // 800nd row 900nd column set to 5
  console.log(`${t}[1][2]: ${A[[1,2]]}, ${t}[800][900]: ${A[[800,900]]}`);
}

log('A', A);
log('B', B);
log('C', C);
log('D', D);
log('E', E);
log('F', F);
log('G', G);
log('H', H);
log('I', I);
log('J', J);
log('K', K);
log('L', L);
log('M', M);
log2('N', N);
This is presentation of solutions - not benchmark

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
21

To create an 4x6 array, simply do this

const x = [...new Array(6)].map(elem => new Array(4))

It's usually a good practice to start with an empty array, rather than filling w random values. (You normally declare array as const x = [] in 1D, so better to start w empty in 2D.)

guest
  • 2,185
  • 3
  • 23
  • 46
19

This is what i achieved :

var appVar = [[]];
appVar[0][4] = "bineesh";
appVar[0][5] = "kumar";
console.log(appVar[0][4] + appVar[0][5]);
console.log(appVar);

This spelled me bineeshkumar

Ruslan López
  • 4,433
  • 2
  • 26
  • 37
Bineesh
  • 494
  • 1
  • 5
  • 18
  • 3
    Notice how you can only access the 0 index of the parent array. This isn't as useful as something which allows you to set, for example, appVar[5][9] = 10; ... you would get 'Unable to set property "9" of undefined' with this. – RaisinBranCrunch Jul 30 '17 at 16:38
  • But `appVar[1][4] = "bineesh";` is wrong, how to solve it? – Gank May 20 '18 at 13:50
  • 1
    @RaisinBran and @Gank This creates only one row with dynamic multiple columns. If you want to have multiple rows, you can do something like this: `var appVar = [[], [], [], [], [], []];` This will create 6 rows with each dynamic multiple columns. – Abdulwehab Aug 09 '22 at 08:29
18

Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1].

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"
TJ L
  • 23,914
  • 7
  • 59
  • 77
17

For one liner lovers Array.from()

// creates 8x8 array filed with "0"    
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))

Another one (from comment by dmitry_romanov) use Array().fill()

// creates 8x8 array filed with "0"    
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))

Using ES6+ spread operator ("inspired" by InspiredJW answer :) )

// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))
my-
  • 604
  • 9
  • 17
  • 3
    we can remove `0` in the first `fill()` function: `const arr2d = Array(8).fill().map(() => Array(8).fill("0"));` – Jinsong Li Nov 21 '17 at 14:38
15

I'm not sure if anyone has answered this but I found this worked for me pretty well -

var array = [[,],[,]]

eg:

var a = [[1,2],[3,4]]

For a 2 dimensional array, for instance.

Nikson Kanti Paul
  • 3,394
  • 1
  • 35
  • 51
Uchenna
  • 159
  • 1
  • 2
15

To create a non-sparse "2D" array (x,y) with all indices addressable and values set to null:

let 2Darray = new Array(x).fill(null).map(item =>(new Array(y).fill(null))) 

bonus "3D" Array (x,y,z)

let 3Darray = new Array(x).fill(null).map(item=>(new Array(y).fill(null)).map(item=>Array(z).fill(null)))

Variations and corrections on this have been mentioned in comments and at various points in response to this question but not as an actual answer so I am adding it here.

It should be noted that (similar to most other answers) this has O(x*y) time complexity so it probably not suitable for very large arrays.

Justin Ohms
  • 3,334
  • 31
  • 45
13

To create a 2D array in javaScript we can create an Array first and then add Arrays as it's elements. This method will return a 2D array with the given number of rows and columns.

function Create2DArray(rows,columns) {
   var x = new Array(rows);
   for (var i = 0; i < rows; i++) {
       x[i] = new Array(columns);
   }
   return x;
}

to create an Array use this method as below.

var array = Create2DArray(10,20);
prime
  • 14,464
  • 14
  • 99
  • 131
  • 2
    Please would you add some explanatory information to your ansdwer showing how it works, and why it solves the problem. This will help others who find this page in the future – Our Man in Bananas Jun 25 '14 at 12:16
  • When would you need an Array that is preinitialized with a certain number of colums in Javascript? You can access the n-th element of a [] array as well. – domenukk Jul 08 '14 at 14:49
  • I noticed the function starts with capital C, which (by certain conventions) suggest it would be a Function constructor and you would use it with the new keyword. A very minor and somewhat opinionated maybe, but I would still suggest un-capitalized word. – Hachi Aug 24 '14 at 05:53
13

Row and Column sizes of an array known only at the run time then following method could be used for creating a dynamic 2d array.

    var num = '123456';
    var row = 3; // Known at run time
    var col = 2; // Known at run time
    var i = 0;
    
    var array2D = [[]];
    for(var r = 0; r < row; ++r)
    {
        array2D[r] = [];
        for(var c = 0; c < col; ++c)
        {
            array2D[r][c] = num[i++];
        }
    }
    console.log(array2D); 
    // [[ '1', '2' ], 
    //  [ '3', '4' ], 
    //  [ '5', '6' ]]
    
    console.log(array2D[2][1]); // 6
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
SridharKritha
  • 8,481
  • 2
  • 52
  • 43
  • Works well, but shouldn't col and row be swapped? Your visual representation seems to go against the convention of rows being horizontal, and columns being vertical. – Chewie The Chorkie Feb 23 '21 at 00:54
12

Use Array Comprehensions

In JavaScript 1.7 and higher you can use array comprehensions to create two dimensional arrays. You can also filter and/or manipulate the entries while filling the array and don't have to use loops.

var rows = [1, 2, 3];
var cols = ["a", "b", "c", "d"];

var grid = [ for (r of rows) [ for (c of cols) r+c ] ];

/* 
         grid = [
            ["1a","1b","1c","1d"],
            ["2a","2b","2c","2d"],
            ["3a","3b","3c","3d"]
         ]
*/

You can create any n x m array you want and fill it with a default value by calling

var default = 0;  // your 2d array will be filled with this value
var n_dim = 2;
var m_dim = 7; 

var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]] 
/* 
         arr = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
         ]
*/

More examples and documentation can be found here.

Please note that this is not a standard feature yet.

Tim Hallyburton
  • 2,741
  • 1
  • 21
  • 29
  • A quick google check here... yup... the `for` statement is still a loop... – Pimp Trizkit Mar 10 '18 at 15:25
  • 1
    It is not supported by any browser - [HERE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions)? – Kamil Kiełczewski Jan 21 '20 at 14:56
11
Array(m).fill(v).map(() => Array(n).fill(v))

You can create a 2 Dimensional array m x n with initial value m and n can be any numbers v can be any value string, number, undefined.

One approach can be var a = [m][n]

Alex
  • 1,457
  • 1
  • 13
  • 26
Chirag Agrawal
  • 183
  • 2
  • 7
  • I like your answer, but you don't need to use map(), you can do it with fill() alone, like this: var map = new Array(height).fill(new Array(width).fill(val)); creating an array like so: map[y][x] = val; – Tornseglare Dec 09 '20 at 17:07
10

The following example defines a two-dimensional array named activities:

    let activities = [
        ['Work', 9],
        ['Eat', 1],
        ['Commute', 2],
        ['Play Game', 1],
        ['Sleep', 7]
    ];

In the activities array, the first dimension represents the activity and the second one shows the number of hours spent per day for each.

To show the activities array in the console, you use the console.table() method as follows:

console.table(activities);

The following illustrates the output:

┌─────────┬─────────────┬───┐
│ (index) │      0      │ 1 │
├─────────┼─────────────┼───┤
│    0    │   'Work'    │ 9 │
│    1    │    'Eat'    │ 1 │
│    2    │  'Commute'  │ 2 │
│    3    │ 'Play Game' │ 1 │
│    4    │   'Sleep'   │ 7 │
└─────────┴─────────────┴───┘

Note that the (index) column is for the illustration that indicates the indices of the inner array.

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.

The following example returns the second element of the first inner array in the activities array above:

console.log(activities[0][1]); // 9

Adding elements to the JavaScript multidimensional array

You can use the Array methods such as push() and splice() to manipulate elements of a multidimensional array.

For example, to add a new element at the end of the multidimensional array, you use the push() method as follows:

activities.push(['Study',2]);
┌─────────┬─────────────┬───┐
│ (index) │      0      │ 1 │
├─────────┼─────────────┼───┤
│    0    │   'Work'    │ 9 │
│    1    │    'Eat'    │ 1 │
│    2    │  'Commute'  │ 2 │
│    3    │ 'Play Game' │ 1 │
│    4    │   'Sleep'   │ 7 │
│    5    │   'Study'   │ 2 │
└─────────┴─────────────┴───┘

To insert an element in the middle of the array, you use the splice() method. The following inserts an element in the second position of the activities array:

activities.splice(1, 0, ['Programming', 2]);
┌─────────┬───────────────┬───┐
│ (index) │       0       │ 1 │
├─────────┼───────────────┼───┤
│    0    │    'Work'     │ 9 │
│    1    │ 'Programming' │ 2 │
│    2    │     'Eat'     │ 1 │
│    3    │   'Commute'   │ 2 │
│    4    │  'Play Game'  │ 1 │
│    5    │    'Sleep'    │ 7 │
│    6    │    'Study'    │ 2 │
└─────────┴───────────────┴───┘

This example calculates the percentage of the hours spent on each activity and appends the percentage to the inner array.

activities.forEach(activity => {
    let percentage = ((activity[1] / 24) * 100).toFixed();
    activity[2] = percentage + '%';
});
┌─────────┬───────────────┬───┬───────┐
│ (index) │       0       │ 1 │   2   │
├─────────┼───────────────┼───┼───────┤
│    0    │    'Work'     │ 9 │ '38%' │
│    1    │ 'Programming' │ 2 │ '8%'  │
│    2    │     'Eat'     │ 1 │ '4%'  │
│    3    │   'Commute'   │ 2 │ '8%'  │
│    4    │  'Play Game'  │ 1 │ '4%'  │
│    5    │    'Sleep'    │ 7 │ '29%' │
│    6    │    'Study'    │ 2 │ '8%'  │
└─────────┴───────────────┴───┴───────┘

Removing elements from the JavaScript multidimensional array

To remove an element from an array, you use the pop() or splice() method.

For example, the following statement removes the last element of the activities array:

activities.pop();
┌─────────┬───────────────┬───┬───────┐
│ (index) │       0       │ 1 │   2   │
├─────────┼───────────────┼───┼───────┤
│    0    │    'Work'     │ 9 │ '38%' │
│    1    │ 'Programming' │ 2 │ '8%'  │
│    2    │     'Eat'     │ 1 │ '4%'  │
│    3    │   'Commute'   │ 2 │ '8%'  │
│    4    │  'Play Game'  │ 1 │ '4%'  │
│    5    │    'Sleep'    │ 7 │ '29%' │
└─────────┴───────────────┴───┴───────┘

Similarly, you can remove the elements from the inner array of the multidimensional array by using the pop() method. The following example removes the percentage element from the inner arrays of the activities array.

activities.forEach((activity) => {
    activity.pop(2);
});
┌─────────┬───────────────┬───┐
│ (index) │       0       │ 1 │
├─────────┼───────────────┼───┤
│    0    │    'Work'     │ 9 │
│    1    │ 'Programming' │ 2 │
│    2    │     'Eat'     │ 1 │
│    3    │   'Commute'   │ 2 │
│    4    │  'Play Game'  │ 1 │
│    5    │    'Sleep'    │ 7 │
└─────────┴───────────────┴───┘

Iterating over elements of the JavaScript multidimensional array

To iterate a multidimensional array, you use a nested for loop as in the following example.

// loop the outer array

for (let i = 0; i < activities.length; i++) {
    // get the size of the inner array
    var innerArrayLength = activities[i].length;
    // loop the inner array
    for (let j = 0; j < innerArrayLength; j++) {
        console.log('[' + i + ',' + j + '] = ' + activities[i][j]);
    }
}

The first loop iterates over the elements of the outer array and the nested loop iterates over elements of the inner array.

The following shows the output of the script in the console:

[0,0] = Work
[0,1] = 9
[1,0] = Eat
[1,1] = 1
[2,0] = Commute
[2,1] = 2
[3,0] = Play Game
[3,1] = 1
[4,0] = Sleep
[4,1] = 7
[5,0] = Study
[5,1] = 2

Or you can use the forEach() method twice:

activities.forEach((activity) => {
    activity.forEach((data) => {
        console.log(data);
    });
});
Work
9
Eat
1
Commute
2
Play Game
1
Sleep
7
Study
2
PJProudhon
  • 835
  • 15
  • 17
devMoki
  • 301
  • 4
  • 12
8

I found below is the simplest way:

var array1 = [[]];   
array1[0][100] = 5; 
    
alert(array1[0][100]);
alert(array1.length);
alert(array1[0].length);
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
Sam YC
  • 10,725
  • 19
  • 102
  • 158
  • `array1[1][100] = 666;` throws `Uncaught TypeError: Cannot set property '100' of undefined` – Kamil Kiełczewski Jan 21 '20 at 14:35
  • @KamilKiełczewski you are right, looks like this only initiate for the first array of array, for the second before you do `array1[1][100] = 666;`, you need to do this `array1[1] = [];`. – Sam YC Jan 22 '20 at 01:22
8

My approach is very similar to @Bineesh answer but with a more general approach.

You can declare the double array as follows:

var myDoubleArray = [[]];

And the storing and accessing the contents in the following manner:

var testArray1 = [9,8]
var testArray2 = [3,5,7,9,10]
var testArray3 = {"test":123}
var index = 0;

myDoubleArray[index++] = testArray1;
myDoubleArray[index++] = testArray2;
myDoubleArray[index++] = testArray3;

console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],) 

This will print the expected output

[ 9, 8 ] 9 123
7

var playList = [
  ['I Did It My Way', 'Frank Sinatra'],
  ['Respect', 'Aretha Franklin'],
  ['Imagine', 'John Lennon'],
  ['Born to Run', 'Bruce Springsteen'],
  ['Louie Louie', 'The Kingsmen'],
  ['Maybellene', 'Chuck Berry']
];

function print(message) {
  document.write(message);
}

function printSongs( songs ) {
  var listHTML;
  listHTML = '<ol>';
  for ( var i = 0; i < songs.length; i += 1) {
    listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';
  }
  listHTML += '</ol>';
  print(listHTML);
}

printSongs(playList);
antelove
  • 3,216
  • 26
  • 20
6

Below one, creates a 5x5 matrix and fill them with null

var md = [];
for(var i=0; i<5; i++) {
    md.push(new Array(5).fill(null));
}

console.log(md);
Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56
zeah
  • 254
  • 4
  • 7
  • 3
    This answer is wrong. It will create an array with same array filling in its slots. `md[1][0] = 3` and all the rest of elements are updated too – Qiang Nov 15 '16 at 06:33
6

ES6+, ES2015+ can do this in even simpler way


Creating 3 x 2 Array filled with true

[...Array(3)].map(item => Array(2).fill(true))
jwchang
  • 10,584
  • 15
  • 58
  • 89
  • I need to confess. I "adopted" your answer and added to [mine](https://stackoverflow.com/a/44864925/5322506), the one-liners collection. – my- Jan 24 '20 at 21:06
5

I had to make a flexible array function to add "records" to it as i needed and to be able to update them and do whatever calculations e needed before i sent it to a database for further processing. Here's the code, hope it helps :).

function Add2List(clmn1, clmn2, clmn3) {
    aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
    aLine.splice(aPos, 0,aColumns);  // Inserts new "record" at position aPos in main array
    aColumns = [];    // Resets temporary array
    aPos++ // Increments position not to overlap previous "records"
}

Feel free to optimize and / or point out any bugs :)

CJ Mendes
  • 314
  • 5
  • 11
5

Javascript does not support two dimensional arrays, instead we store an array inside another array and fetch the data from that array depending on what position of that array you want to access. Remember array numeration starts at ZERO.

Code Example:

/* Two dimensional array that's 5 x 5 

       C0 C1 C2 C3 C4 
    R0[1][1][1][1][1] 
    R1[1][1][1][1][1] 
    R2[1][1][1][1][1] 
    R3[1][1][1][1][1] 
    R4[1][1][1][1][1] 
*/

var row0 = [1,1,1,1,1],
    row1 = [1,1,1,1,1],
    row2 = [1,1,1,1,1],
    row3 = [1,1,1,1,1],
    row4 = [1,1,1,1,1];

var table = [row0,row1,row2,row3,row4];
console.log(table[0][0]); // Get the first item in the array
Rick
  • 12,606
  • 2
  • 43
  • 41
5

Here's a quick way I've found to make a two dimensional array.

function createArray(x, y) {
    return Array.apply(null, Array(x)).map(e => Array(y));
}

You can easily turn this function into an ES5 function as well.

function createArray(x, y) {
    return Array.apply(null, Array(x)).map(function(e) {
        return Array(y);
    });
}

Why this works: the new Array(n) constructor creates an object with a prototype of Array.prototype and then assigns the object's length, resulting in an unpopulated array. Due to its lack of actual members we can't run the Array.prototype.map function on it.

However, when you provide more than one argument to the constructor, such as when you do Array(1, 2, 3, 4), the constructor will use the arguments object to instantiate and populate an Array object correctly.

For this reason, we can use Array.apply(null, Array(x)), because the apply function will spread the arguments into the constructor. For clarification, doing Array.apply(null, Array(3)) is equivalent to doing Array(null, null, null).

Now that we've created an actual populated array, all we need to do is call map and create the second layer (y).

dimiguel
  • 1,429
  • 1
  • 16
  • 37
5

One liner to create a m*n 2 dimensional array filled with 0.

new Array(m).fill(new Array(n).fill(0));
geniuscarrier
  • 4,199
  • 2
  • 21
  • 15
  • 3
    Actually, this will create only two arrays. Second dimensions is going to be the same array in every index. – Pijusn Mar 07 '17 at 19:07
  • 7
    Yes, I confirm the gotcha. Quick fix: `a = Array(m).fill(0).map(() => Array(n).fill(0))` ? `map` will untie reference and create unique array per slot. – dmitry_romanov Apr 15 '17 at 04:28
5

There is another solution, that does not force you to pre-define the size of the 2d array, and that is very concise.

var table = {}
table[[1,2]] = 3 // Notice the double [[ and ]]
console.log(table[[1,2]]) // -> 3

This works because, [1,2] is transformed into a string, that is used as a string key for the table object.

Oli
  • 15,935
  • 7
  • 50
  • 66
  • This answer alone makes me not want to mess with the junk that is "multi-dimensional" arrays in JavaScript, even tho I have a very elegant solution.This also illustrates that everyone else isn't actually making multidimensional arrays at all.Just like an "array" in JavaScript; this answer will completely "simulate" a pseudo-infinite sized, infinite dimension array of arbitrary sizes and contents.All the other recursion and loop based answers have a much lower upper limit to the size of the array structure they can create.And the creation speed will be a major issue for these larger structures. – Pimp Trizkit Mar 10 '18 at 16:27
  • Use this line instead to simulate pre-filling: `var table = new Proxy({}, {get:(t,n)=>n in t ? t[n] : 42});` – Pimp Trizkit Mar 10 '18 at 17:11
  • Nice, creative way to 'emulate' Array2D by object :) – Kamil Kiełczewski Jan 21 '20 at 15:19
3

I found that this code works for me:

var map = [
    []
];

mapWidth = 50;
mapHeight = 50;
fillEmptyMap(map, mapWidth, mapHeight);

...

function fillEmptyMap(array, width, height) {
    for (var x = 0; x < width; x++) {
        array[x] = [];
        for (var y = 0; y < height; y++) {

            array[x][y] = [0];
        }
    }
}
Fabced
  • 63
  • 7
3

A simplified example:

var blocks = [];

blocks[0] = [];

blocks[0][0] = 7;
Anders
  • 8,307
  • 9
  • 56
  • 88
rickatech
  • 551
  • 4
  • 10
3

I'm not a fan of the ES6 solutions using .fill(). Some may work but the extra hoops to avoid the copy-by-reference problems make them non-intuitive.

My suggested ES6 approach is to fully leverage the spread operator for both outer and inner arrays. It's easier to reason about IMO.

[...Array(3)].map(() => [...Array(4)])

If you need to set an initial value, then you chain on a .map() on the inner array creation:

[...Array(3)].map(() => [...Array(4)].map(() => 0))

Lastly, a type-safe TypeScript util function:

export const createMultiDimensionalArray = <T>(
  n: number,
  m: number,
  initialVal?: T,
): T[][] => {
  const matrix = [...Array(n)].map(() => [...Array(m)]);
  return initialVal === undefined
    ? matrix
    : matrix.map(r => r.map(() => initialVal));
};

Examples using it:

const a = createMultiDimensionalArray(1, 2);
a[1][2] = 3;     // Works

const b = createMultiDimensionalArray(2, 3, false);
b[1][2] = true;  // Works
b[1][2] = 3;     // Error: Type '3' is not assignable to type 'boolean'.
ravishi
  • 3,349
  • 5
  • 31
  • 40
3

use the global object Array and fill items with arrays:

let arr = new Array(5).fill([]);

or if the 2d array of known length:

let arr = new Array(5).fill(new Array(2));
Hossam
  • 367
  • 3
  • 9
  • 2nd one in the or is not correct! Because it creates a shallow copy of Array(2) at each index of the first array. So if you set arr[0][0] = 1 then it will modify the arr[1][0], arr[2][0], arr[3][0] and so on ..... to 1 also. – Riyad Zaigirdar Jan 04 '23 at 05:00
3

You could allocate an array of rows, where each row is an array of the same length. Or you could allocate a one-dimensional array with rows*columns elements and define methods to map row/column coordinates to element indices.

Whichever implementation you pick, if you wrap it in an object you can define the accessor methods in a prototype to make the API easy to use.

Nat
  • 9,820
  • 3
  • 31
  • 33
2

I've made a modification of Matthew Crumley's answer for creating a multidimensional array function. I've added the dimensions of the array to be passed as array variable and there will be another variable - value, which will be used to set the values of the elements of the last arrays in the multidimensional array.

/*
*   Function to create an n-dimensional array
*
*   @param array dimensions
*   @param any type value
*
*   @return array array
 */
function createArray(dimensions, value) {
    // Create new array
    var array = new Array(dimensions[0] || 0);
    var i = dimensions[0];

    // If dimensions array's length is bigger than 1
    // we start creating arrays in the array elements with recursions
    // to achieve multidimensional array
    if (dimensions.length > 1) {
        // Remove the first value from the array
        var args = Array.prototype.slice.call(dimensions, 1);
        // For each index in the created array create a new array with recursion
        while(i--) {
            array[dimensions[0]-1 - i] = createArray(args, value);
        }
    // If there is only one element left in the dimensions array
    // assign value to each of the new array's elements if value is set as param
    } else {
        if (typeof value !== 'undefined') {
            while(i--) {
                array[dimensions[0]-1 - i] = value;
            }
        }
    }

    return array;
}

createArray([]);              // [] or new Array()

createArray([2], 'empty');    // ['empty', 'empty']

createArray([3, 2], 0);       // [[0, 0],
                              //  [0, 0],
                              //  [0, 0]]
Community
  • 1
  • 1
Hristo Enev
  • 2,421
  • 18
  • 29
2

Recursive function to create a multi-dimensional array:

var makeArray = function (dims, arr) {          
    if (dims[1] === undefined) {
        return new Array(dims[0]);
    }

    arr = new Array(dims[0]);

    for (var i=0; i<dims[0]; i++) {
        arr[i] = new Array(dims[1]);
        arr[i] = makeArray(dims.slice(1), arr[i]);
    }

    return arr;
}

Build a 2x3x4x2 4D-Array:

var array = makeArray([2, 3, 4, 2]);    
chessweb
  • 4,613
  • 5
  • 27
  • 32
2
 var items = [
      ["January 01", 42.5],
      ["February 01",  44.3],
      ["March 01",  28.7],
      ["April 01",  44.3],
      ["May 01",  22.9],
      ["June 01",  54.4],
      ["July 01",  69.3],
      ["August 01",  19.1],
      ["September 01",  82.5],
      ["October 01",  53.2],
      ["November 01",  75.9],
      ["December 01",  58.7]

    ];
  alert(items[1][0]); // February 01
  alert(items[5][1]); // 54.4
Juboraj Sarker
  • 947
  • 1
  • 9
  • 13
2
const arr = new Array(5).fill(new Array(5).fill(0));
console.log(arr);
Manish
  • 485
  • 4
  • 3
  • 8
    Since this is answer is the shown as the first result I just want to mention that (like others already mentioned) in this solution the second dimension arrays are copied by reference so this may not be the best way to create a 2D array – air5 Jul 12 '21 at 21:34
  • @air5 You seem to be unaware that sorting order is not predicatable. There is no such think as "first" here. The order is individually configurable. – Yunnosch Aug 17 '21 at 06:14
  • 1
    This actually messed me up at first. Since it is filling the 2nd dimension with the first array by reference, any change made to any array will affect all arrays in the the 2nd dimension. – jfunk Oct 11 '21 at 03:07
1

You can also create a function to create a 2D array like this:

var myTable = [];

function createArray(myLength) {
    myTable = new Array(myLength);
    var cols, rows;
    for (cols = 0; cols < myLength; cols++) {
        myTable[cols] = new Array(myLength);
    }
}

You can call it by using the following, which will give you a 10x10 2D array.

createArray(10);

You also can create a 3D array using this method.

1

nodejs + lodash version:

var _ = require("lodash");
var result = _.chunk(['a', 'b', 'c', 'd', 'e', 'f'], 2);
console.log(result);
console.log(result[2][0]);

The output:

[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ] ]
e
mpiliszcz
  • 397
  • 4
  • 5
1
Array.from({length: rows}).map(e => new Array(columns));
Error404
  • 719
  • 9
  • 30
1

My solution won't be the best one, But just giving my solutions to create user-defined multidimensional array.

This function accepting rows and columns,

function createArray(row,column) {
let arr = [];

for(var i=0; i<row; i++){
    arr[i] = [Math.floor(Math.random() * (10))];

    for(var j=0;j<column;j++){
        arr[i][j]= [Math.floor(Math.random() * (20))];
    }
}

return arr;
}

var arrVal = createArray(4, 5);

console.log(arrVal);
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Javascript Coder
  • 5,691
  • 8
  • 52
  • 98
1

This constructs arrays of any dimension.

function makeArrayChildren(parent, firstDimension, ...dimensions) {
  for (let i = 0; i < parent.length; i++) {
    parent[i] = new Array(firstDimension);
    if (dimensions.length != 0) {
      makeArrayChildren(parent[i], ...dimensions);
    }
  }
}
function makeArray(firstDimension, ...dimensions) {
  if (firstDimension == undefined) {
    throw Exception("Too few dimensions");
  }
  let topArray = new Array(firstDimension);
  if (dimensions.length != 0) makeArrayChildren(topArray, ...dimensions);
  return topArray;
}

Here's another two functions I wanted to make, which I can use as a sanity check: a for each that executes on all the lowest level items in a multi dimensional array and a fill method.

Array.prototype.dimensionalFill = function (value) {
  for (let i = 0; i < this.length; i++) {
    const elem = this[i];
    if (elem instanceof Array) {
      elem.dimensionalFill(value);
    } else {
      this[i] = value;
    }
  }
};
/*Unlike forEach, this also loops over undefined values. */
Array.prototype.dimensionalForEach = function (callableFunc, thisArg) {
  if (thisArg != undefined) {
    return this.dimensionalForEach(callableFunc.bind(thisArg));
  }
  for (let i = 0; i < this.length; i++) {
    const elem = this[i];
    if (elem instanceof Array) {
      elem.dimensionalForEach(callableFunc);
    } else {
      callableFunc(elem, i, this);
    }
  }
};

And here's a nice little sanity check that uses all the features. So at the very least, it can't be completely wrong.

let arr = makeArray(10, 10, 5, 4);
arr.dimensionalFill(2);
let sum = 0;
arr.dimensionalForEach((elem) => {
  sum += elem;
});
console.log(`sum: ${sum} === ${10 * 10 * 5 * 4 * 2}`);

It bears mentioning that at this point, it would've been a far better practice to create an altogether new structure, but this was fun.

JadeSpy
  • 140
  • 1
  • 8
0

If you are after 2D array for google charts, the best way to do it is

var finalData = [];
[["key",value], ["2013-8-5", 13.5], ["2013-7-29",19.7]...]

referring to Not a valid 2d array google chart

Community
  • 1
  • 1
Bishoy Hanna
  • 4,539
  • 1
  • 29
  • 31
0
var _field = (function()
{
    var array = [];
    for(var y = 0; y != 3; y++) { array[y] = new Array(5); }
    return array;
})();

// var item = _field[2][4];
Martin Wantke
  • 4,287
  • 33
  • 21
0

What happens if the size of array is unknown? Or array should be dynamically created and populated? Alternative solution which worked for me is to use class with static 2d array variable which in case of non-existence of index in array will initiate it:

function _a(x,y,val){
    // return depending on parameters
    switch(arguments.length){
        case 0: return _a.a;
        case 1: return _a.a[x];
        case 2: return _a.a[x][y];
    }

    // declare array if wasn't declared yet
    if(typeof _a.a[x] == 'undefined')
        _a.a[x] = [];

    _a.a[x][y] = val;
}
// declare static empty variable
_a.a = [];

The syntax will be:

_a(1,1,2); // populates [1][1] with value 2
_a(1,1);   // 2 or alternative syntax _a.a[1][1]
_a(1);     // [undefined × 1, 2]
_a.a;      // [undefined × 1, Array[2]]
_a.a.length
NGix
  • 2,542
  • 8
  • 28
  • 39
0

An awesome repository here .

  • api : masfufa.js

  • sample : masfufa.html

Two Examples will be enough to understand this library :

Example 1:

   /*     | 1 , 2 , 3 |
    * MX= | 4 , 5 , 6 |     Dimensions= 3 x 3
    *     | 7 , 8 , 9 |
    */ 


  jsdk.getAPI('my');
  var A=[1, 2, 3, 4, 5, 6, 7, 8, 9];
  var MX=myAPI.getInstance('masfufa',{data:A,dim:'3x3'});

then :

MX.get[0][0]  // -> 1 (first)
MX.get[2][2] //  ->9 (last)

Example 2:

   /*      | 1 , 9 , 3 , 4 |
    * MXB= | 4 , 5 , 6 , 2 |     Dimensions= 2 x 4
    *   
    */ 

  var B=[1 , 9 , 3 , 4 , 4 , 5 , 6 , 2];
  var MXB=myAPI.getInstance('masfufa',{data:B,dim:'2x4'});

then :

MXB.get[0][0]  // -> 1 (first)
MXB.get[1][3] //  -> 2 (last)
MXB.get[1][2] //  -> 6 (before last)
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
0

This is mentioned in a few of the comments, but using Array.fill() will help construct a 2-d array:

function create2dArr(x,y) {
    var arr = [];
    for(var i = 0; i < y; i++) {
        arr.push(Array(x).fill(0));
    }
    return arr; 
}

this will result in an array of length x, y times in the returned array.

efong5
  • 366
  • 1
  • 6
  • 21
0

This is my implementation of Multi-Dimension Array.

In this approach, I am creating a single dimension array

I have added a prototype function multi to Array object, Which can be used to create any dimension Array.

I have also added a prototype function index to Array object, Which can be used to get index in linear Array from multi-dimension indexes.

Creating a Array

//Equivalent to arr[I][J][K]..[] in C
var arr = new Array().multi(I,J,K,..);

Accessing array value at any index

//Equivalent in C arr[i][j][k];
var vaue = arr[arr.index(i,j,k)];

SNIPPET

/*
   Storing array as single dimension 
   and access using Array.index(i,j,k,...)
*/


Array.prototype.multi = function(){
 this.multi_size = arguments;
 this.multi_len = 1
 for(key in arguments) this.multi_len *=  arguments[key];
 for(var i=0;i<this.multi_len;i++) this.push(0);
 return this;
}

Array.prototype.index = function(){
   var _size = this.multi_len;
   var temp = 1;
   var index = 0;
   for(key in arguments) {
      temp*=this.multi_size[key];
      index+=(arguments[key]*(_size/temp))
   }
   return index;
}

// Now you can use the multi dimension array
// A 3x3 2D Matrix

var arr2d = new Array().multi(3,3); // A 2D Array
arr2d[arr2d.index(1,1,1)]  = 5;
console.log(arr2d[arr2d.index(1,1,1)]);

// A 3x3x3 3D Matrix

var arr3d = new Array().multi(3,3,3); // a 3D Array
arr3d[arr3d.index(1,1,1)]  = 5;
console.log(arr3d[arr3d.index(1,1,1)]);

// A 4x3x3 4D Matrix
var arr4d = new Array().multi(4,3,3,3); // a 4D Array
arr4d[arr4d.index(4,0,0,1)]  = 5;
console.log(arr4d[arr4d.index(4,0,0,1)]);
Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33
0

If all you want is a 4x4 matrix have a look at DOMMatrix, it is easy to use I can say,

let m = new DOMMatrix(); 
// m.m11, m.m12, m.m13, m.m14, ..., m.m41, m.m42, m.m43, m.m44

Initially brought for different reasons, it is not available on node.js and only limited to 4x4.

Also you can consider using an auto-vivification object instead arrays for JS, have a look at my answer here but brought here also for more convince:

var tree = () => new Proxy({}, { get: (target, name) => name in target ? target[name] : target[name] = tree() });

var t = tree();
t[0][2][3] = 4;
console.log(t[0][2][3]);

It uses new JS and acts not correctly when you iterate through it so be careful with it.

Also have a look at this if you need a flexible multi-dimension array generator.

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81
0

Creates n dimensional matrix array for Java Script, filling with initial default of value 0.

function arr (arg, def = 0){
      if (arg.length > 2){
        return Array(arg[0]).fill().map(()=>arr(arg.slice(1)));
      } else {
        return Array(arg[0]).fill().map(()=>Array(arg[1]).fill(def));
      }
    }

// Simple Usage of 4 dimensions
var s = arr([3,8,4,6])

// Use null default value with 2 dimensions
var k = arr([5,6] , null)
Bircan
  • 29
  • 3