Skip to content

How to get the position information of a value of an array inside loop

I need to get the information of a position of an array inside the loop.

I’ve two variables.

var columns = 4, 
    rows = 5;

So, the array would be look like this according to the value of i (in loop):

enter image description here

Now, I’ve to produce an array of information.

var positions = [], 
    totalCount = columns * rows;

for (var i = 1; i <= totalCount; i++) {
    var informationObject = {
        "column": "column number",
        "row": "row number",
        "column_count": "column count",
        "row_count": "row count",
    };

    positions.push(informationObject);
}

console.log(positions);

Detailed architecture of this is here:

enter image description here

I wan’t to prepare this positions array differently according to the position information.

You may ask me what I’ve tried. I actually doing it custom code. Like if(i=7){//do operation}, I mean totally humanize code. This is getting very weird. I think there has a way to do this dynamically.

Please help. Thanks in advance.

Answer

Hard-coding the output based on i is not a viable solution. The property values you are looking to output can be obtained through the use of the Modulo operator (%) and division:

var columns = 4,
  rows = 5,
  positions = [],
  totalCount = columns * rows;

for (var i = 0; i < totalCount; i++) {
  let r = Math.ceil(i / columns);
  let c = (i % columns) + 1;
  
  positions.push({
    column: c,
    row: r,
    column_count: r,
    row_count: c
  });
}

console.log(positions);

For further information see the following MDN links: