1

I try to create a two-dimensional Array filled with Objects like this:

Array[5][1] = Objekt //start from 5 & 1 instead of 0 & 0 
Array[6][1] = Objekt    
Array[7][1] = Objekt    
Array[9][1] = Objekt //skipped 8   
Array[10][1] = Objekt 

Array[2][2] = Objekt  
Array[3][2] = Objekt  
Array[4][2] = Objekt  
Array[6][2] = Objekt //skipped 5
Array[7][2] = Objekt

Array[3][3] = Objekt
Array[4][3] = Objekt
Array[5][3] = Objekt
Array[6][3] = Objekt
Array[8][3] = Objekt //skipped 7

My problem is: I don't can start from zero so I can't use the push function. That's because It's a grid. The first index is the X, the 2nd the Y position of the grid cube. (Three.js)

That's the object:

var grid =
[   
    //line 1
    {x:5,z:1},
    {x:6,z:1},
    {x:7,z:1},
    {x:9,z:1},
    {x:10,z:1},

    //line 2
    {x:2,z:2},
    {x:3,z:2},
    {x:4,z:2},
    {x:6,z:2},
    {x:7,z:2},

    //line 3
    {x:3,z:3},
    {x:4,z:3},
    {x:5,z:3},
    {x:6,z:3},
    {x:8,z:3},

    //..
};

But how can I create a Array like the top example instead of an array like arr[0][0], arr[0][1], arr[0][2], arr[1][0], arr[1][1], .. ? Is it even possible?

4
  • Yes, it is possible. What seems to be a problem? Commented Jan 23, 2015 at 3:44
  • 1
    @PM 77-1: The problem seems to be that I don't know how to create a Array like this. Commented Jan 23, 2015 at 3:48
  • You will need to do it by explicitly specifying index values. Like in your first example. Commented Jan 23, 2015 at 3:51
  • 1
    @PM 77-1: You mean like: arr = []; arr[5] = []; arr[5][1] = new Object(); arr[5][2] = new Object(); and so on for each one? Commented Jan 23, 2015 at 3:57

1 Answer 1

2

Since your objects contain the information where you want to position them in the array, you can achieve this with a simple loop:

var newArray = [];

grid.forEach(function(obj) {
    if (!newArray[obj.x]) {
        newArray[obj.x] = [];
    }
    newArray[obj.x][obj.z] = obj;
});

Iterating over all objects is also pretty easy. forEach skips holes:

newArray.forEach(function(innerArray) {
    innerArray.forEach(function(obj) {
        console.log(obj);
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Nice one. Thank you, I didnt knew that !arr[index] works like typeof(arr[index]) != 'undefined'. You helped me a lot, thank you.
Well, technically !newArray[obj.x] simply converts the value of newArray[obj.x] to a boolean and negates the value. E.g. !0 is true as well. However, since your array is either undefined at that position or an array, this check is safe to use here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.