0

I want to predefine the 2d-array containing an array of objects like this below image: enter image description here

I am trying this way:

var grid = [];
iMax = 3;
jMax = 2;
count = 0;

    for (let i = 0; i < iMax; i++) {
      grid[i] = [];

      for (let j = 0; j < jMax; j++) {
        grid[i][j] = count;
        count++;
      }
    }
2
  • Can you show us what you've tried and where you're stuck? Commented Apr 4, 2021 at 9:23
  • I know in java how to do it. But in javascript unable to figure out. Commented Apr 4, 2021 at 9:29

1 Answer 1

1

In your code you're building up the two-dimensional array, but you are filling the rows with numbers (i.e. your setting the count) instead of an array of objects. So if you want to achieve the exact same structure as provided in the screenshot, you can do:

const rows = 4;
const cols = 4;
const elementCount = 3;



function buildGrid(rows,cols, elementCount) {
  const grid = [];
  for(let i=0; i < rows; i++) {
    grid[i] = [];
    for(let j=0; j < cols; j++) {
      grid[i].push(Array.from({length:elementCount}, () => ({})));
    }

  }
  return grid;
}

const grid = buildGrid(rows,cols,elementCount);
console.log(grid);

Sign up to request clarification or add additional context in comments.

Comments

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.