How to Create a 2D Array in JavaScript

JavaScript does not have a special syntax for creating multidimensional arrays. To create a 2D array in JavaScript, we have to create an array and then make each element of the array an array as well. That means we create an array of arrays.

Example:


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

The problem with this approach is that each element of the array is set to undefined. Douglas Crockford (JavaScript: The Good Parts, p.64) proposes an extension of the JavaScript array object:

Array.matrix = function(numrows, numcols, initial){
   var arr = [];
   for (var i = 0; i < numrows; ++i){
      var columns = [];
      for (var j = 0; j < numcols; ++j){
         columns[j] = initial;
      }
      arr[i] = columns;
    }
    return arr;
}

Usage:


//create a 8x8 matrix, with all values set to 0
var my2Darray = Array.matrix(8,8,0);

console.log(my2Darray[3][3]); // displays 0

Patterns used to process elements in a 2D array

Accessing Elements by Columns


var grades = [[89,77,78],[76,82,81],[91,94,89]];
var total = 0;
var average = 0.0;

for (var row = 0; row < grades.length; ++row){
	//inner loop is controlled by the expression grades[rows].length
	for (var col = 0; col < grades[row].length; ++col){
		total += grades[row][col];
	}

	average = total / grades[row].length;
	console.log("Student "  + parseInt(row+1) +
				" average: " + average.toFixed(2));
	total = 0;
	average = 0.0;
}

/*
  Output:
  Student 1 average: 81.33
  Student 2 average: 79.67
  Student 3 average: 91.33
*/

Accessing Elements by Rows

Same as columns, except a flip in the loop occur


var grades = [[89,77,78],[76,82,81],[91,94,89]];
var total = 0;
var average = 0.0;

for (var col = 0; col < grades.length; ++col){
	//inner loop is controlled by the expression grades[cols].length
	for (var row = 0; row < grades[col].length; ++row){
		total += grades[row][col];
	}

	average = total / grades[col].length;
	console.log("Test "  + parseInt(col+1) +
				" average: " + average.toFixed(2));
	total = 0;
	average = 0.0;
}

/*
  Output:
  Test 1 average: 85.33
  Test 2 average: 84.33
  Test 3 average: 82.67
*/

Posted on: March 26th, 2014 by Stephani

Leave a Reply