JavaScript two-dimensional array | Create example

  • by

JavaScript two-dimensional array is an array of arrays. Two-dimensional arrays are a collection of homogeneous elements that span over multiple rows and columns, assuming the form of a matrix.

var arr = [
  ["aaa", "bbb"],
  ["ddd", "eee"]
];

Technically, there is no two-dimensional array in JavaScript. JavaScript supports 2D arrays through jagged arrays – an array of arrays. Jagged arrays are essentially multiple arrays jagged together to form a multidimensional array.

JavaScript two-dimensional array

Simple example program to Create Two Dimensional Arrays.

Just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call array push(), the pair of values will be placed at index 0.

<!DOCTYPE html>
<html>
<body>

  <script>
    var arry = [];
    arry.push([1,2]);
    arry.push([3,4]);

    console.log(arry)
  </script>

</body>
</html> 

Output:

JavaScript two-dimensional array

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2-dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

arry.push(100);

Source: stackoverflow.com

Two Dimensional Array Using for Loop

function twoDimensionArray(a, b) {
    let arr = [];

    // creating two dimensional array
    for (let i = 0; i< a; i++) {
        for(let j = 0; j< b; j++) {
            arr[i] = [];
        }
    }

    // inserting elements to array
    for (let i = 0; i< a; i++) {
        for(let j = 0; j< b; j++) {
            arr[i][j] = j;
        }
    }
    return arr;
}

const x = 2;
const y = 3;

const result = twoDimensionArray(x, y);
console.log(result);

Output: [[0, 1, 2], [0, 1, 2]]

Do comment if you have any doubts or suggestions on this Js Arra 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.