Skip to content

JavaScript 2D Array | Creating and Accessing example

  • by

JavaScript only has 1-dimensional arrays, but you can build 2D Array using arrays of arrays. The two-dimensional array is a collection of items that share a common name and they are organized as a matrix in the form of rows and columns.

var items = [
  [1, 2],
  [3, 4],
  [5, 6]
];

To create an array, it’s better to use the square bracket notation ( [] ):

var myArray = [];

This is the way you emulate a multi-dimensional array in JavaScript. It’s one or more arrays inside an array.

var myArray = [
    [], [] // two arrays
];

You can access them like this:

myArray[0][0]; // the 1st element of the first array in myArray
myArray[1][1]; // the 2nd element of the second array in myArray

JavaScript 2D Array example

A simple example code creates 2 Multidimensional Array.

<!DOCTYPE html>
<html>
<body>
  <script>
    let arr1 = ['A', 24];
    let arr2 = ['B', 23];
    let arr3 = ['C', 24];

    // multidimensional array
    let arr2d = [arr1, arr2, arr3];

    console.log(arr2d)
  </script>
</body>
</html> 

Output:

JavaScript 2D Array

To access the elements of a multidimensional array using indices (0, 1, 2 …).


let x = [
    ['A', 1],
    ['B', 2], 
    ['C', 3]
    ];

    // access the first item 
    console.log(x[0]);

    // access the first item of the first inner array
    console.log(x[0][0]);


    // access the second item of the third inner array
    console.log(x[2][1]);

Output:

access the elements of a 2 multidimensional

Use the Array’s push() method or an indexing notation to add elements to a multidimensional array.

<script>
let x = [
    [0, 1],
    [5, 2], 
    [6, 3]];

    x.push([7,4])
    console.log(x)

</script>

Use the Array’s pop() method to remove the element from a multidimensional array.

  x.pop()

You can also use the for...of loop to iterate over the multidimensional array.

<script>
  let x = [
    [0, 1],
    [5, 2], 
    [6, 3]];

    for (let i of x) {
      for (let j of i) {
        console.log(j);
      }
    }

</script>

Here’s an example of how you might print a 2D array:

for (let i = 0; i < twoDArray.length; i++) {
  for (let j = 0; j < twoDArray[i].length; j++) {
    console.log(`Row ${i}, Column ${j}: ${twoDArray[i][j]}`);
  }
}

This code will iterate through each element of the 2D array and print its value along with its row and column indices.

Do comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading