[javascript] How can I create a two dimensional array in JavaScript?

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]?)

This question is related to javascript arrays multidimensional-array

The answer is


var _field = (function()
{
    var array = [];
    for(var y = 0; y != 3; y++) { array[y] = new Array(5); }
    return array;
})();

// var item = _field[2][4];

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

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"

A simplified example:

var blocks = [];

blocks[0] = [];

blocks[0][0] = 7;

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

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

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


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.


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)]

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);

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

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

_x000D_
_x000D_
function A(r) {_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < r; i++) arr[i] = [];_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function B(r, c) {_x000D_
  var arr = new Array(r);_x000D_
  for (var i = 0; i < arr.length; i++) arr[i] = new Array(c);_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function C(r, c) {_x000D_
  var arr = Array(r);_x000D_
  for (var i = 0; i < arr.length; i++) arr[i] = Array(c);_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function D(r, c) {_x000D_
  // strange, but works_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < r; i++) {_x000D_
    arr.push([]);_x000D_
    arr[i].push(Array(c));_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function E(r, c) {_x000D_
  let array = [[]];_x000D_
  for (var x = 0; x < c; x++) {_x000D_
    array[x] = [];_x000D_
    for (var y = 0; y < r; y++) array[x][y] = [0];_x000D_
  }_x000D_
  return array;_x000D_
}_x000D_
_x000D_
function F(r, c) {_x000D_
  var makeArray = function(dims, arr) {_x000D_
    if (dims[1] === undefined) {_x000D_
      return Array(dims[0]);_x000D_
    }_x000D_
_x000D_
    arr = Array(dims[0]);_x000D_
_x000D_
    for (var i = 0; i < dims[0]; i++) {_x000D_
      arr[i] = Array(dims[1]);_x000D_
      arr[i] = makeArray(dims.slice(1), arr[i]);_x000D_
    }_x000D_
_x000D_
    return arr;_x000D_
  }_x000D_
  return makeArray([r, c]);_x000D_
}_x000D_
_x000D_
function G(r) {_x000D_
  var a = [];_x000D_
  while (a.push([]) < r);_x000D_
  return a;_x000D_
}_x000D_
_x000D_
function H(r,c) {_x000D_
  function createArray(length) {_x000D_
    var arr = new Array(length || 0),_x000D_
        i = length;_x000D_
_x000D_
    if (arguments.length > 1) {_x000D_
        var args = Array.prototype.slice.call(arguments, 1);_x000D_
        while(i--) arr[length-1 - i] = createArray.apply(this, args);_x000D_
    }_x000D_
_x000D_
    return arr;_x000D_
  }_x000D_
  return createArray(r,c);_x000D_
}_x000D_
_x000D_
function I(r, c) {_x000D_
  return [...Array(r)].map(x => Array(c));_x000D_
}_x000D_
_x000D_
function J(r, c) {_x000D_
  return Array(r).fill(0).map(() => Array(c));_x000D_
}_x000D_
_x000D_
function K(r, c) {_x000D_
  return Array.from(Array(r), () => Array(c));_x000D_
}_x000D_
_x000D_
function L(r, c) {_x000D_
  return Array.from({length: r}).map(e => Array(c));_x000D_
}_x000D_
_x000D_
function M(r, c) {_x000D_
  return Array.from({length: r}, () => Array.from({length: c}, () => {}));_x000D_
}_x000D_
_x000D_
function N(r, c) {_x000D_
  return {}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// -----------------------------------------------_x000D_
// SHOW_x000D_
// -----------------------------------------------_x000D_
_x000D_
log = (t, f) => {_x000D_
  let A = f(3, 4); // create array with 3 rows and 4 columns_x000D_
  A[1][2] = 6 // 2-nd row 3nd column set to 6_x000D_
  console.log(`${t}[1][2]: ${A[1][2]}, full: ${JSON.stringify(A).replace(/null/g,'x')}`);_x000D_
}_x000D_
_x000D_
log2 = (t, f) => {_x000D_
  let A = f(3, 4); // create array with 3 rows and 4 columns_x000D_
  A[[1,2]] = 6 // 2-nd row 3nd column set to 6_x000D_
  console.log(`${t}[1][2]: ${A[[1,2]]}, full: ${JSON.stringify(A).replace(/null/g,'x')}`);_x000D_
}_x000D_
_x000D_
log('A', A);_x000D_
log('B', B);_x000D_
log('C', C);_x000D_
log('D', D);_x000D_
log('E', E);_x000D_
log('F', F);_x000D_
log('G', G);_x000D_
log('H', H);_x000D_
log('I', I);_x000D_
log('J', J);_x000D_
log('K', K);_x000D_
log('L', L);_x000D_
log('M', M);_x000D_
log2('N', N);
_x000D_
This is presentation of solutions - not benchmark
_x000D_
_x000D_
_x000D_

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

_x000D_
_x000D_
function A(r, c, def) {_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < r; i++) arr[i] = Array(c).fill(def);_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function B(r, c, def) {_x000D_
  var arr = new Array(r);_x000D_
  for (var i = 0; i < arr.length; i++) arr[i] = new Array(c).fill(def);_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function C(r, c, def) {_x000D_
  var arr = Array(r);_x000D_
  for (var i = 0; i < arr.length; i++) arr[i] = Array(c).fill(def);_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function D(r, c, def) {_x000D_
  // strange, but works_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < r; i++) {_x000D_
    arr.push([]);_x000D_
    arr[i].push(Array(c));_x000D_
  }_x000D_
  for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[i][j]=def_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
function E(r, c, def) {_x000D_
  let array = [[]];_x000D_
  for (var x = 0; x < c; x++) {_x000D_
    array[x] = [];_x000D_
    for (var y = 0; y < r; y++) array[x][y] = def;_x000D_
  }_x000D_
  return array;_x000D_
}_x000D_
_x000D_
function F(r, c, def) {_x000D_
  var makeArray = function(dims, arr) {_x000D_
    if (dims[1] === undefined) {_x000D_
      return Array(dims[0]).fill(def);_x000D_
    }_x000D_
_x000D_
    arr = Array(dims[0]);_x000D_
_x000D_
    for (var i = 0; i < dims[0]; i++) {_x000D_
      arr[i] = Array(dims[1]);_x000D_
      arr[i] = makeArray(dims.slice(1), arr[i]);_x000D_
    }_x000D_
_x000D_
    return arr;_x000D_
  }_x000D_
  return makeArray([r, c]);_x000D_
}_x000D_
_x000D_
function G(r, c, def) {_x000D_
  var a = [];_x000D_
  while (a.push(Array(c).fill(def)) < r);_x000D_
  return a;_x000D_
}_x000D_
_x000D_
function H(r,c, def) {_x000D_
  function createArray(length) {_x000D_
    var arr = new Array(length || 0),_x000D_
        i = length;_x000D_
_x000D_
    if (arguments.length > 1) {_x000D_
        var args = Array.prototype.slice.call(arguments, 1);_x000D_
        while(i--) arr[length-1 - i] = createArray.apply(this, args).fill(def);_x000D_
    }_x000D_
_x000D_
    return arr;_x000D_
  }_x000D_
  return createArray(r,c);_x000D_
}_x000D_
_x000D_
function I(r, c, def) {_x000D_
  return [...Array(r)].map(x => Array(c).fill(def));_x000D_
}_x000D_
_x000D_
function J(r, c, def) {_x000D_
  return Array(r).fill(0).map(() => Array(c).fill(def));_x000D_
}_x000D_
_x000D_
function K(r, c, def) {_x000D_
  return Array.from(Array(r), () => Array(c).fill(def));_x000D_
}_x000D_
_x000D_
function L(r, c, def) {_x000D_
  return Array.from({length: r}).map(e => Array(c).fill(def));_x000D_
}_x000D_
_x000D_
function M(r, c, def) {_x000D_
  return Array.from({length: r}, () => Array.from({length: c}, () => def));_x000D_
}_x000D_
_x000D_
function N(r, c, def) {_x000D_
  let arr={};_x000D_
  for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[[i,j]]=def;_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// -----------------------------------------------_x000D_
// SHOW_x000D_
// -----------------------------------------------_x000D_
_x000D_
log = (t, f) => {_x000D_
  let A = f(1000,1000,7); // create array with 1000 rows and 1000 columns, _x000D_
                          // each array cell initilised by 7_x000D_
  A[800][900] = 5         // 800nd row and 901nd column set to 5_x000D_
  console.log(`${t}[1][2]: ${A[1][2]}, ${t}[800][901]: ${A[800][900]}`);_x000D_
}_x000D_
_x000D_
log2 = (t, f) => {_x000D_
  let A = f(1000,1000,7); // create array with 1000 rows and 1000 columns, _x000D_
                          // each array cell initilised by 7_x000D_
  A[[800,900]] = 5            // 800nd row 900nd column set to 5_x000D_
  console.log(`${t}[1][2]: ${A[[1,2]]}, ${t}[800][900]: ${A[[800,900]]}`);_x000D_
}_x000D_
_x000D_
log('A', A);_x000D_
log('B', B);_x000D_
log('C', C);_x000D_
log('D', D);_x000D_
log('E', E);_x000D_
log('F', F);_x000D_
log('G', G);_x000D_
log('H', H);_x000D_
log('I', I);_x000D_
log('J', J);_x000D_
log('K', K);_x000D_
log('L', L);_x000D_
log('M', M);_x000D_
log2('N', N);
_x000D_
This is presentation of solutions - not benchmark
_x000D_
_x000D_
_x000D_

enter image description here


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)

The sanest answer seems to be

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


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);

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];
        }
    }
}

This is what i achieved :

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

This spelled me bineeshkumar


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

You simply make each item within the array an array.

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


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.


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.


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).


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 :)


 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

_x000D_
_x000D_
var playList = [_x000D_
  ['I Did It My Way', 'Frank Sinatra'],_x000D_
  ['Respect', 'Aretha Franklin'],_x000D_
  ['Imagine', 'John Lennon'],_x000D_
  ['Born to Run', 'Bruce Springsteen'],_x000D_
  ['Louie Louie', 'The Kingsmen'],_x000D_
  ['Maybellene', 'Chuck Berry']_x000D_
];_x000D_
_x000D_
function print(message) {_x000D_
  document.write(message);_x000D_
}_x000D_
_x000D_
function printSongs( songs ) {_x000D_
  var listHTML;_x000D_
  listHTML = '<ol>';_x000D_
  for ( var i = 0; i < songs.length; i += 1) {_x000D_
    listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';_x000D_
  }_x000D_
  listHTML += '</ol>';_x000D_
  print(listHTML);_x000D_
}_x000D_
_x000D_
printSongs(playList);
_x000D_
_x000D_
_x000D_


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"))

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.


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)

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.


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]


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]]

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'

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.)


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)


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.


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


I found below is the simplest way:

_x000D_
_x000D_
var array1 = [[]];   
array1[0][100] = 5; 
    
alert(array1[0][100]);
alert(array1.length);
alert(array1[0].length);
_x000D_
_x000D_
_x000D_


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.

_x000D_
_x000D_
    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
_x000D_
_x000D_
_x000D_


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.


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]])

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

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.

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


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.

_x000D_
_x000D_
var arr = Array(2).fill(Array(4));_x000D_
arr[0][0] = 'foo';_x000D_
console.info(arr);_x000D_
console.info(arr[0][0], arr[1][0]);
_x000D_
_x000D_
_x000D_


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

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


Array.from({length: rows}).map(e => new Array(columns));

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

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.


The easiest way:

var myArray = [[]];

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'.

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]);    

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

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;
// ...

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))

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

new Array(m).fill(new Array(n).fill(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

_x000D_
_x000D_
/*_x000D_
   Storing array as single dimension _x000D_
   and access using Array.index(i,j,k,...)_x000D_
*/_x000D_
_x000D_
_x000D_
Array.prototype.multi = function(){_x000D_
 this.multi_size = arguments;_x000D_
 this.multi_len = 1_x000D_
 for(key in arguments) this.multi_len *=  arguments[key];_x000D_
 for(var i=0;i<this.multi_len;i++) this.push(0);_x000D_
 return this;_x000D_
}_x000D_
_x000D_
Array.prototype.index = function(){_x000D_
   var _size = this.multi_len;_x000D_
   var temp = 1;_x000D_
   var index = 0;_x000D_
   for(key in arguments) {_x000D_
      temp*=this.multi_size[key];_x000D_
      index+=(arguments[key]*(_size/temp))_x000D_
   }_x000D_
   return index;_x000D_
}_x000D_
_x000D_
// Now you can use the multi dimension array_x000D_
// A 3x3 2D Matrix_x000D_
_x000D_
var arr2d = new Array().multi(3,3); // A 2D Array_x000D_
arr2d[arr2d.index(1,1,1)]  = 5;_x000D_
console.log(arr2d[arr2d.index(1,1,1)]);_x000D_
_x000D_
// A 3x3x3 3D Matrix_x000D_
_x000D_
var arr3d = new Array().multi(3,3,3); // a 3D Array_x000D_
arr3d[arr3d.index(1,1,1)]  = 5;_x000D_
console.log(arr3d[arr3d.index(1,1,1)]);_x000D_
_x000D_
// A 4x3x3 4D Matrix_x000D_
var arr4d = new Array().multi(4,3,3,3); // a 4D Array_x000D_
arr4d[arr4d.index(4,0,0,1)]  = 5;_x000D_
console.log(arr4d[arr4d.index(4,0,0,1)]);
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array