ChatGPT解决这个技术问题 Extra ChatGPT

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.

How do I declare a 2 dimensional array in JavaScript? (assuming it's possible) How would I access its members? (myArray[0][1] or myArray[0,1]?)

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.
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.
a = Array(5).fill(0).map(x => Array(10).fill(0))
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: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@kalehmann that is fine: 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.

A
Adam

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


It would be difficult to initialize a large multidimensional array this way. However, this function can be used to create an empty multidimensional, with the dimensions specified as parameters.
@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
@SashikaXP, this does not work for first indices other than 0.
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.
I believe this is a jagged array (array of arrays) - Does JavaScript have a difference between jagged and multidimensional as some other languages do?
v
vsync

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


Can they use things like strings for their keys and values? myArray['Book']['item1'] ?
@Diego, yes, but that's not what arrays are intended for. It's better to use an object when your keys are strings.
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.
doesn't work - error on assignment. How has this answer got 280 likes if it is useless?
This is working, thanks. You can see the example Gargo jsfiddle.net/matasoy/oetw73sj
y
yckart

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

Can this create a 4 dimensional array?
@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);.
Best answer ! However, I would not recommend to use it with 0 or 1 parameters (useless)
@BritishDeveloper Yes. 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]]]]]
@haykam sorry to waste your time - I was being sarcastic :/
T
Trent

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


I suggest this: Array.from({length:5}, () => [])
Subjective here but this answer (the first and second within it) seems like the best balance of succinct, fast, and modern.
@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
Best one-liner answer!
what is the difference between Array.from(Array(2), () => new Array(4)) and Array.from(Array(2), () => Array(4))?
P
Philippe Leybaert

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

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.
function Create2DArray(rows) { var arr = []; for (var i=0;i
@Doug: You actually want a one-dimensional array of objects with 2 attributes. var deck= []; deck[0]= { face:1, suit:'H'};
@DougHauf that's a minified 2D-array ?? :P :D
F
Fred

The easiest way:

var myArray = [[]];

which is a 2-dimension array
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 you have to set myArray[1]=[]; before assigning myArray[1][0]=5;
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.
@182764125216 that was knowledge of the day for me. Thanks :)
J
James Conigliaro

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.


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.
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.
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.
@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.)
S
Sergio Abreu

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

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.
for javascript world, this is the perfect solutions. Thank you very much for providing this solutions
You are so kind AMIC
d
domenukk

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)


One-liner: for (var a=[]; a.push([])<10;);?
@Bergi will the a variable still be defined in the next line..?
@StinkyCat: Yes, that's how var works. It's always function-scoped.
I know, therefore your one-liner is useless in this case: you cannot "access its members" (check question)
domenukk and @Bergi, you're both correct. I tried it out and I can access a after the for. I apologize! and thank you, may this be a lesson to me ;)
G
Giorgi Moniava

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

This should be at the very top. I did something similar using Array.apply(null, Array(nrows)) but this is much more elegant.
This regard my last comment... Internet Explorer and Opera don't have support for fill. This won't work on a majority of browsers.
@dimgl Fill can be emulated in this instance with a constant map: Array(nrows).map(() => 0), or, Array(nrows).map(function(){ return 0; });
C
Chicharito

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'

K
Kamil Kiełczewski

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

https://i.stack.imgur.com/YD4S1.png

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

https://i.stack.imgur.com/y0zh2.png

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

https://i.stack.imgur.com/oBoCA.png


g
guest

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


R
Ruslan López

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


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.
But appVar[1][4] = "bineesh"; is wrong, how to solve it?
T
TJ L

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"

N
Nikson Kanti Paul

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.


How can I do this dynamically? I want the inner arrays with different sizes.
You don't need extra commas var array = [[],[]] is adequate.
J
Justin Ohms

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.


be careful because fill set the same value. if change null to `object it will be the same object in every column
@StanislavMayorov If you want to set each cell's value, just use the same trick: let 2Darray = new Array(x).fill(null).map(item =>(new Array(y).fill(null).map(cell =>(yourValueHere))))
p
prime

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

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
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.
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.
m
my-

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

we can remove 0 in the first fill() function: const arr2d = Array(8).fill().map(() => Array(8).fill("0"));
T
Tim Hallyburton

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.


A quick google check here... yup... the for statement is still a loop...
It is not supported by any browser - HERE?
A
Alex
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 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;
R
Ran Marciano

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


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.
A
Alexander

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

R
Ran Marciano

I found below is the simplest way:

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


array1[1][100] = 666; throws Uncaught TypeError: Cannot set property '100' of undefined
@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] = [];.
a
antelove

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

    '; for ( var i = 0; i < songs.length; i += 1) { listHTML += '
  1. ' + songs[i][0] + ' by ' + songs[i][1] + '
  2. '; } listHTML += '
'; print(listHTML); } printSongs(playList);


j
jwchang

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

I need to confess. I "adopted" your answer and added to mine, the one-liners collection.
C
CJ Mendes

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


How about just aLine.push([clmn1, clmn2, clmn3]); ?
R
Rick

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

d
dimiguel

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


g
geniuscarrier

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

new Array(m).fill(new Array(n).fill(0));

Actually, this will create only two arrays. Second dimensions is going to be the same array in every index.
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.