I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.

  1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)

  2. How would I access its members? (myArray[0][1] or myArray[0,1]?)

Thanks

share|improve this question
feedback

13 Answers

up vote 157 down vote accepted
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
share|improve this answer
   
The easiest example so far :) +1 – itsols Jul 17 '12 at 3:49
feedback

Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1].

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]); //alerts "4"
share|improve this answer
feedback

You simply make each item within the array an array.

  var x = new Array(10);
  for (var i = 0; i < 10; i++) {
    x[i] = new Array(20);
  }
  x[5][12] = 3.0;
share|improve this answer
4  
Can they use things like strings for their keys and values? myArray['Book']['item1'] ? – Diego Jun 8 '09 at 19:54
9  
@Diego, yes, but that's not what arrays are intended for. It's better to use an object when your keys are strings. – Matthew Crumley Jun 8 '09 at 20:05
feedback

Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.

The following function can be used to construct a 2-d array of fixed dimensions:

function Create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}

The number of columns is not really important, because it is not required to specify the size of an array before using it.

Then you can just call:

var arr = Create2DArray(100);

arr[50][2] = 5;
arr[70][5] = 7454;
// ...
share|improve this answer
feedback

You could allocate an array of rows, where each row is an array of the same length. Or you could allocate a one-dimensional array with rows*columns elements and define methods to map row/column coordinates to element indices.

Whichever implementation you pick, if you wrap it in an object you can define the accessor methods in a prototype to make the API easy to use.

share|improve this answer
feedback

The reason some say that it isn't possible is because a two dimensional array is really just an array of arrays. The other comments here provide perfectly valid methods of creating two dimensional arrays in JavaScript, but the purest point of view would be that you have a one dimensional array of objects, each of those objects would be a one dimensional array consisting of two elements.

So, that's the cause of the conflicting view points.

share|improve this answer
12  
No, it's not. In some languages, you can have multidimensional arrays like string[3,5] = "foo";. It's a better approach for some scenarios, because the Y axis is not actually a child of the X axis. – Rafael Soares Aug 4 '11 at 15:29
feedback

Similar to activa's answer, here's a function to create an n-dimensional array:

function createArray(length) {
    var a = new Array(length || 0);

    if (arguments.length > 1) {
        var args = Array.prototype.slice.call(arguments, 1);
        for (var i = 0; i < length; i++) {
            a[i] = createArray.apply(this, args);
        }
    }

    return a;
}

createArray();     // [] or new Array()

createArray(2);    // new Array(2)

createArray(3, 2); // [new Array(2),
                   //  new Array(2),
                   //  new Array(2)]
share|improve this answer
Can this create a 4 dimensional array? – trusktr May 19 '11 at 2:18
@trusktr: Yes, you could create as many dimensions as you want (within your memory constraints). Just pass in the length of the four dimensions. For example, var array = createArray(2, 3, 4, 5);. – Matthew Crumley May 19 '11 at 4:21
Nice! I actually asked about this here: stackoverflow.com/questions/6053332/javascript-4d-arrays and a variety of interesting answers. – trusktr May 19 '11 at 5:50
feedback

property type array in JavaScript

var model = {};

model.Action = [];

model.Caption = [];

model.Step = [];
share|improve this answer
feedback

I'm not sure if anyone has answered this but I found this worked for me pretty well -

var array = [[,],[,]]

eg:

var a = [[1,2],[3,4]]

For a 2 dimensional array, for instance.

share|improve this answer
feedback

I had to make a flexible array function to add "records" to it as i needed and to be able to update them and do whatever calculations e needed before i sent it to a database for further processing. Here's the code, hope it helps :).

function Add2List(clmn1, clmn2, clmn3) {
    aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
    aLine.splice(aPos, 0,aColumns);  // Inserts new "record" at position aPos in main array
    aColumns = [];    // Resets temporary array
    aPos++ // Increments position not to overlap previous "records"
}

Feel free to optimize and / or point out any bugs :)

share|improve this answer
feedback

I wanted create a three dimensional array on the fly. In this example, I create a class to encapsulate an array of pro sports teams.

function ClassTeams ()  
{  
    this.aaastrTeamsByLeagueCityYear = [];  

    // to add element to array
    function addTeam (strLeague, strCity, nYear, strTeam)  
    {
        if ((typeof this.aaastrTeamsByLeagueCityYear[strLeague]) === "undefined")
        {   // first element from this league.  Need to create array.
            this.aaastrTeamsByLeagueCityYear[strLeague] = [];
        }
        if ((typeof this.aaastrTeamsByLeagueCityYear[strLeague][strCity]) === "undefined")
        {   // first element for this city in this league.  Need to create array.
            this.aaastrTeamsByLeagueCityYear[strLeague][strCity] = [];
        }
        this.aaastrTeamsByLeagueCityYear[strLeague][strCity][nYear] = strTeam;
    };

    // get element from array
    function getTeam (strLeague, strCity, nYear)
    {
        return (this.aaastrTeamsByLeagueCityYear[strLeague][strCity][nYear]);
    };

    // list all elements in array
    function showTeams ()
    {
        var strLeague;
        var strCity;
        var nYear;
        var strHtml="<table>";

        strHtml += "<tr>";
        strHtml += "<th>League</th>";
        strHtml += "<th>City</th>";
        strHtml += "<th>Year</th>";
        strHtml += "<th>Team</th>";
        strHtml += "</tr>";

        for (strLeague in this.aaastrTeamsByLeagueCityYear);
        {
            for (strCity in this.aaastrTeamsByLeagueCityYear[strLeague]);
            {
                for (nYear in this.aaastrTeamsByLeagueCityYear[strLeague][strCity]);
                {
                    strHtml += "<tr>";
                    strHtml += "<td>" + strLeague + "</td>";
                    strHtml += "<td>" + strCity + "</td>";
                    strHtml += "<td>" + nYear + "</td>";
                    strHtml += "<td>" + this.aaastrTeamsByLeagueCityYear[strLeague][strCity][nYear] + "</td>";
                    strHtml += "</tr>";
                }
            }
        }
        strHtml+="</table>";
        return (strHtml);
    };

    // create function to show all teams in given league
    // because League is in the primary array, this is relatively easy
    this.showLeagueTeams = function (strLeague)
    {
        // don't need local variable to traverse League
        var strCity;
        var nYear;
        var strHtml="<table>";

        strHtml += "<tr>";
        strHtml += "<th>League</th>";
        strHtml += "<th>City</th>";
        strHtml += "<th>Year</th>";
        strHtml += "<th>Team</th>";
        strHtml += "</tr>";

        // no need to traverse primary array, array of leagues.
        for (strCity in this.aaastrTeamsByLeagueCityYear[strLeague]);
        {
            for (nYear in this.aaastrTeamsByLeagueCityYear[strLeague][strCity]);
            {
                strHtml += "<tr>";
                strHtml += "<td>" + strLeague + "</td>";
                strHtml += "<td>" + strCity + "</td>";
                strHtml += "<td>" + nYear + "</td>";
                strHtml += "<td>" + this.aaastrTeamsByLeagueCityYear[strLeague][strCity][nYear] + "</td>";
                strHtml += "</tr>";
            }
        }
        strHtml+="</table>";
        return (strHtml);
    };

    // create function to show all teams for a given city
    // because City is in a secondary array, this is a little more complicated
    this.showCityTeams = function (strMyCity)
    {
        var strLeague;
        var strCity; // do need local variable to traverse cities
        var nYear;
        var strHtml="<table>";

        strHtml += "<tr>";
        strHtml += "<th>League</th>";
        strHtml += "<th>City</th>";
        strHtml += "<th>Year</th>";
        strHtml += "<th>Team</th>";
        strHtml += "</tr>";

        for (strLeague in this.aaastrTeamsByLeagueCityYear);
        {
            for (strCity in this.aaastrTeamsByLeagueCityYear[strLeague]);
            {   // check all the cities of the given league
                if (strCity == strMyCity)
                {   // this is where we limit display to particular city
                    for (nYear in this.aaastrTeamsByLeagueCityYear[strLeague][strCity]);
                    {
                        strHtml += "<tr>";
                        strHtml += "<td>" + strLeague + "</td>";
                        strHtml += "<td>" + strCity + "</td>";
                        strHtml += "<td>" + nYear + "</td>";
                        strHtml += "<td>" + this.aaastrTeamsByLeagueCityYear[strLeague][strCity][nYear] + "</td>";
                        strHtml += "</tr>";
                    }
                }
            }
        }
        strHtml+="</table>";
        return (strHtml);
    };
}

use it

var objTeams = new ClassTeams ();
objTeams.addTeam ("NFL","Detroit",2012,"Lions");
objTeams.addTeam ("MLB","Detroit",2012,"Tigers");
objTeams.addTeam ("NFL","Chicago",2012,"Bears");
objTeams.showTeams (); // show all 3 teams
objTeams.showLeagueTeams ("NFL"); // show both NFL teams
objTeams.showCityTeams ("Detroit"); // show both Detroit teams
// etc
share|improve this answer
please edit your answer and format the code to make it readable – kleopatra Nov 8 '12 at 17:25
Yes, edit this and use the code sample tags instead of html so it's in accord with the rest of the site please. – Tim Gautier Nov 8 '12 at 17:39
feedback

The easiest way:

var myArray = [[]];
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.