How to Create a Two Dimensional Array in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Create an Array of Arrays
JavaScript does not support two-dimensional associative arrays. However, you can simulate the effect of two dimensional arrays in JavaScript by creating an array of arrays.
Let's take a look at the following example to understand how it basically works:
Example
Try this code »// Sample array
var arr = [
["a", "Apple"],
["b", "Banana"],
["c", "Cat"],
];
// Accessing array elements
console.log(arr[0][0]); // Prints: a
console.log(arr[0][1]); // Prints: Apple
console.log(arr[1][0]); // Prints: b
console.log(arr[1][1]); // Prints: Banana
console.log(arr[arr.length - 1][0]); // Prints: c
console.log(arr[arr.length - 1][1]); // Prints: Cat
Further, to create such arrays you could do something as shown in the following example:
Example
Try this code »// Creating an empty array
var arr = [];
// Populating array with values
arr[0] = ["a", "Apple"];
arr[1] = ["b", "Banana"];
arr[2]= ["c", "Cat"];
console.log(arr);
Related FAQ
Here are some more FAQ related to this topic: