0

How can I create two 2-DArrays where each element of array is an object with properties . Both arrays are of different size and property of each cell is different.

var gridcell = [];
var regionalcell = [];

So far I have done this, It works but its not efficient i dont want to repeat the code. It would be great if you guys can help.

In both functions value of "w,h,r,c" is different.

function createCellArray(w, h,r,c) 
{
     for (j = 0; j < r; j++) 
     {
         gridcell[j] = [];
       for (i = 0; i < c; i++) 
       {
         gridcell[j][i] = 
            {
                 "x1": w * i,
                 "y1": h * j,
                 "x2": w * (i + 1),
                 "cell_color": null,
                 "y2": h * (j + 1),
                 "name": (i + 1 * (j * 10)) + 1
            }
        }
     }
}


function createRegionalCellArray(w, h, r, c) {
    for (j = 0; j < r; j++) {
        regional[j] = [];
        for (i = 0; i < c; i++) {
            regional[j][i] =
            {
                "x1": w * i,
                "y1": h * j,
                "x2": w * (i + 1),
                "cell_color": null,
                "y2": h * (j + 1),
                "name": (i + 1 * (j * 10)) + 1
            }
        }
    }
}

1 Answer 1

2

I am not sure to really understand what is your issue... You want to factorize your code?

In this case, just make a function that return your common array:

function returnCellArray(w, h, r, c) 
{
     var cellArray = [];
     for (j = 0; j < r; j++) 
     {
       cellArray[j] = [];
       for (i = 0; i < c; i++) 
       {
         cellArray[j][i] = 
            {
                 "x1": w * i,
                 "y1": h * j,
                 "x2": w * (i + 1),
                 "cell_color": null,
                 "y2": h * (j + 1),
                 "name": (i + 1 * (j * 10)) + 1
            }
        }
     }

     return cellArray;
}

gridCell = returnCellArray(w1, h1, r1, c1);
regionalcell = returnCellArray(w2, h2, r2, c2);
Sign up to request clarification or add additional context in comments.

1 Comment

Actually it seems to work, i think i was trying to use global array instead of local as you have used cellArray

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.