Home > Software engineering >  How to make an 2D array to iterate over?
How to make an 2D array to iterate over?

Time:04-20

I have a table through which i want to get the row and column coordinates , like it table has Row-2 and col-2

Coordinates Row = [0,1] and Col = [0,1,0,1].

Since i'm storing this in an array, I want a better way to store it in 2D array so that i can iterate over it.Considering if table has more than 7 rows and cols is it better to have a 2D array?

Method i wrote stores it in array,how do I make a 2D array in it?

CTable.prototype.GetTableMapping = function(currentTable)
{
    let oRowCount = currentTable.GetRowsCount();
    let oRowMapping = [];
    let oColumnMapping = [];
    let oTableMapping = [oRowMapping = [], oColumnMapping = []];
    for (let i = 0; i < oRowCount; i  )
    {
        let oRow = currentTable.GetRow(i);
        let oCellCount = oRow.GetCellsCount();
        oRowMapping.push(i);

        for (let j = 0; j < oCellCount; j  )
        {
            let oCell = oRow.GetCell(j);
            oColumnMapping.push(j);
        }
    }
    console.log("Table",oTableMapping);
    console.log("Rows",oRowMapping);
    console.log("Columns",oColumnMapping);
    return oTableMapping[oRowMapping,oColumnMapping];
};

Output:
[
   Row = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
   Cols = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
]

CodePudding user response:

Since you already have a double for loop you can use it to create the 2D cells

arr2D[i][j] = oCell;

Complete example (mocking) :

mockTable = { // mocking the portions of your code that i don't know
  GetRowsCount : () => 11,
  GetRow: (x) => ({
    GetCellsCount : () => 4,
    GetCell : (x) => x
  })
}

CTable_prototype_GetTableMapping = function(currentTable)
{
    let oRowCount = currentTable.GetRowsCount();
    const arr2D = Array(oRowCount);
    //let oRowMapping = [];
    //let oColumnMapping = [];
    //let oTableMapping = [oRowMapping = [], oColumnMapping = []];
    for (let i = 0; i < oRowCount; i  )
    {
        let oRow = currentTable.GetRow(i);
        let oCellCount = oRow.GetCellsCount();
        arr2D[i] = Array(oCellCount);
        //oRowMapping.push(i);

        for (let j = 0; j < oCellCount; j  )
        {
            let oCell = oRow.GetCell(j);
            //oColumnMapping.push(j);
            arr2D[i][j] = oCell;
        }
    }
    //console.log("Table",oTableMapping);
    //console.log("Rows",oRowMapping);
    //console.log("Columns",oColumnMapping);
    return arr2D;
};

const theArray = CTable_prototype_GetTableMapping(mockTable);

console.log("cell (1,3)",theArray[1][3])
console.log("full 2D array", theArray)

  • Related