15

I could use some guidance on specifying a dynamic multi dimensional array in javascript. I understand that javascript does not natively define multi dim arrays, but rather an array of an array, ie.

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

or

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

or

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

My issue is that I do not know the actual dimensions, and simply defining the array, as in the second example above, still does not allow for the array to go beyond two record sets. I thought there was a REDIM stmt similar to VB but have not been able to locate anything.

One additional part of my problem is that when I specify the second dimension of the array, as in the example below, the array becomes unreachable outside of the for block.

var Exforsys=new Array(4)
for (i=0; i <4; i++) {
   Exforsys[i]=new Array(4)
}

I am trying to retrieve data from my specific array like this...

 function newTest() {
        var myArray = [[],[]];
      //  myArray[] = new Array(14);

        var recCount = coordsAry.length / 15;
        var n =0;

        var i = 0;
        var s = 0;

        for (i = 0; i < recCount; i++) {
            for (s = 0; s < 15; s++) {
              //  myArray[i] = new Array(14);

                myArray[i][s] = coordsAry[n];
                n++;

              //  alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));

            }
            // var u = 4;
            s = 0;

            alert(myArray[0][3]);
            alert(myArray[0][4]);

            alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));              

        }

coordsAry has 105 records and is flat, {"12","Frank","564", ... etc} this has been proven. After the 2nd record is populated I get this error....

Error: Unable to set value of the property '0': object is null or undefined.

Obviously, my javascript skills are a bit rough to say the least. Any sample code would be greatly appreciated.

Thanks,

htm11h
  • 1,739
  • 8
  • 47
  • 104
  • The ones you say not supported seem to run fine in my browser – nhahtdh Dec 05 '12 at 14:14
  • How are you trying to access the array elements? – NickSlash Dec 05 '12 at 14:24
  • The Problem i see is that only the first two elements of myArr are defined as an array, meaning when i reaches 2 it tries to set `myArr[2][0]` but `myArr[2]` is undefined and therefore has no propertie 0 you should do a check if the element you are accessing is undefined : `if(!myArr[i]) myArr[i] = []` – Moritz Roessler Dec 05 '12 at 14:38
  • I updated my answer btw, please check if it solves your problem. – Wutz Dec 05 '12 at 14:45
  • Check my solution for similar question: http://stackoverflow.com/a/22947768/1617186 – NGix Apr 08 '14 at 20:47

5 Answers5

21

You do not Dim the Array to an actual size,

You can just set an variable on any index to whatever you want

if you want two Dimensions you just could define an array

var arr = []

set an element to another array

arr[0] = []

and put an value inside an element in the "2nd dimension"

arr[0][10] = 10

You only have the elements in the "first dimension" to be an array

You could also do things like placing arrays into arrays

like

var arr = []
var arr1 = [1,2,3]
arr[0] = arr1
console.log(arr[0][2]) //3

And if you have an array and want to push elements in an inner array just do a check if the element is defined, like

var arr = []
for ( var i = 0; i < 5 ; i++) {
    if(!arr[i])
        arr[i] = []
    for ( var j = 0; j < 3 ; j++)
        arr[i][j] = i + " - " + j // Or like this,
        //arr[i].push(i + " " + j) // 
}
console.log( arr[2][3]) // 2 - 3

Given the Code you posted

function newTest() {
    var myArray = [[],[]];
  //  myArray[] = new Array(14);

    var recCount = 15
    var n =0;

    var i = 0;
    var s = 0;

    for (i = 0; i < recCount; i++) {
        if(!myArray[i])
             myArray[i] = []
        for (s = 0; s < 15; s++) {
            console.log(i)

          //  myArray[i] = new Array(14);

            myArray[i][s] = s;
            n++;

          //  alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));

        }
        // var u = 4;
        s = 0;

        alert(myArray[0][3]);
        alert(myArray[0][4]);

        alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));              

    }
}
newTest()

This works for me

Moritz Roessler
  • 8,542
  • 26
  • 51
3

All arrays are dynamic in javascript. You can do things like

var list = [];
list[15] = 15;

And it will simply expand the array to have a length of 16, with the values for the first 15 indexes being undefined (~ null). Thus, your 3 examples of multi-dimensional arrays should all work.

Edit: Just saw that you included your code. You are not initializing the arrays of your first dimension. Your loop should be

for (i = 0; i < recCount; i++) {

    //If the outer array does not have an inner array at this position already, create one
    if (!myArray[i])
        myArray[i] = []; //!!!

        for (s = 0; s < 15; s++) {
          //  myArray[i] = new Array(14);

            myArray[i][s] = coordsAry[n]; //myArray[i] returned null/undefined, when i got bigger then the declared array.
            n++;

          //  alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));

        }
        // var u = 4;
        s = 0;

        alert(myArray[0][3]);
        alert(myArray[0][4]);

        alert("i=" + i + " s=" + s + " Val: " + (myArray[i][s]));              

    }
Wutz
  • 2,246
  • 13
  • 15
  • For some reason it is not working, when I reach the end of the defined array I get this error... Error: Unable to set value of the property '0': object is null or undefined. ****** I know that there is more data to populated the array that has been checked. – htm11h Dec 05 '12 at 14:24
  • How does this indicate multi-dimensional? – htm11h Dec 05 '12 at 14:24
  • Could you update your question with some example code that does not work for you? – Wutz Dec 05 '12 at 14:29
1

Lately, I've been using this syntax for creating a two-dimensional array of fixed rows and columns.

Create 2d array:

new Array(rows).fill(0).map(_ => new Array(cols))

Create 2d array and populate with default value:

new Array(rows).fill(0).map(_ => new Array(cols).fill(0))

Details:

  1. Create a one-dimensional array with given rows by doing - new Array(rows).
  2. So, we fill the values of this array using - .fill(0). This step is needed because the JavaScript array's map method doesn't iterate over empty values.
  3. We iterate over all the elements of our one-dimensional array and make it two-dimensional using .map(_ => new Array(cols)).
Vikas
  • 468
  • 3
  • 8
0

To add an element to an array you can use push(val) (to add the back of the array) or unshift(val) to add to the front of the array. So:

var Exforsys=[];
for (i=0; i <4; i++) {
   Exforsys.push([]);
}
Michoel
  • 834
  • 5
  • 16
0

var rows = 4;
var cols = 3;
const mulDimArray = Array.from(
                        new Array(rows)
                            .fill(0), ele => ele = 
                            new Array(cols).fill(0)
                     )
console.log(mulDimArray);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33