Skip to content

JavaScript Multidimensional Array | Example code

  • by

An Array that contains another array is called a Multidimensional Array in JavaScript. You can simply create and declare multidimensional arrays in JavaScript. In the below code, each element of Array is also another array.

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

Or

let m1 = ['A', 1];
let m2 = ['B', 2];
let m3 = ['C', 3];

// multidimensional array
let studentsData = [m1, m2, m3];

Note: JavaScript does not provide the multidimensional array natively.

A multidimensional array in JavaScript is an array that contains one or more arrays as its elements. These arrays can be of any dimension, and they can contain any type of data as an element.

JavaScript multidimensional array

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

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

    console.log(mArray)
    console.log(typeof(mArray))

  </script>

</body>
</html> 

Output:

JavaScript Multidimensional Array

Access Elements of an Array

You can access elements of a multidimensional array by specifying the index of each dimension.

  <script>

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

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

    // access the first item of the first inner array
    console.log(mArray[0][0]);
  </script>

Output: [ “A”, 1 ]

A

Add an Element to a Multidimensional Array

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

<script>
    let mArray = [['A', 1], ['B', 2], ['C', 3]];

    mArray.push(['X', 100]);

    mArray[1][2] = 'HELLO';

    console.log(mArray)
</script>

Output: [ [ ‘A’, 1 ], [ ‘B’, 2, ‘HELLO’ ], [ ‘C’, 3 ], [ ‘X’, 100 ] ]

Remove an Element from a Multidimensional Array

Use the Array’s pop() method to remove the element from any type of array.

<script>
    let mArray = [['A', 1], ['B', 2], ['C', 3]];

    mArray.pop();
    console.log(mArray)
</script>

Output: [ [ ‘A’, 1 ], [ ‘B’, 2 ] ]

You can also use the splice() method to remove an element at a specified index. For example,

mArray.splice(1,1)

Iterating over Multidimensional Array

Using the Array’s forEach() method, You can loop over a multidimensional array using nested loops.

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

mArray.forEach((student) => {
      student.forEach((data) => {
        console.log(data);
      });
    });

Output:

A
1
B
2
C
3

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