Multidimensional Array In JavaScript

in STEMGeekslast year


Image Source

In JavaScript, there is no any built-in support for working with multidimensional array. However, you can work wit multidimensional array by defining an array inside another array. You can use the following syntax if you want to access any value inside such array: array_name[x][y]. In this post, we will see an example of displaying items in a two dimensional array. Its just an array of my favourite dishes ‎😃. In order to display each element, we will use a nested for-loop. If you are working with a 3D array then you will need 3 for-loops to display the value and so on. In real life projects working with multidimensional array is not really applicable expecially when the size of array is very large. And we use objects to work with such scenarios.

<!DOCTYPE html>
<title>Multidimensional Array</title>
    var dish = [
        ["Crunchy Chicken", "Chicken Lollipop", "Chicken Roast", "Chicken Drumstick"],
        ["Kadai Paneer", "Palak Paneer", "Paneer Tikka", "Paneer Makhani"],
        ["Potato Stick", "Aloo Chop", "Aloo Dum", "Potato Chips"]
    document.write("Dishes: " + "<br><br>");
    for (var i=0; i<4; i++)
        for (var j=0; j<4; j++)
            document.write("[" + i + "]" + " " + "[" + j + "]" + "=" + dish[i][j] + "<br>");

If you run the above code in your browser then you can see the name of dish along with the 2D-array index.