user4485105
user4485105

Reputation:

Create and loop through a multi dimensional Array that doesn't start from zero in JavaScript?

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?

Upvotes: 1

Views: 53

Answers (1)

Felix Kling
Felix Kling

Reputation: 816700

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);
    });
});

Upvotes: 2

Related Questions