1

I was wondering how can I get the multidimensional array like [[A1, B1, C1....],[A2, B2, C2....]];

let grid = [
  []
];
let letters = "abcdefghij".toUpperCase();

// create the Grid
const createGrid = (size) => {
  let row = 0;
  let col = 0;
  for (row = 0; row < size; row++) {
    grid[row] = [];
    for (col = 0; col < letters.length; col++) {
      grid[row][col] = `${letters[row]}${col + 1}`;
    }
  }
};

createGrid(letters.length);
console.log(grid);

1
  • 3
    You can just swap the row and col in your cell assignment like ${letters[col]}${row + 1} Commented Jun 21, 2022 at 14:46

2 Answers 2

2

If you don't mind converting your code to ES6+, this one should do the trick.

const letters = "abcdefghij".toUpperCase();

const createGrid = (letters) => Array.from(
    { length: letters.length },
    (_, index) => [...letters].map((letter) => `${letter}${index + 1}`)
);

console.log(createGrid(letters));

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

Comments

1

Just refer the col instead of the row and concat the row + 1 to it in the inner loop when you are doing the assignment.

let grid = [
  []
];
let letters = "abcdefghij".toUpperCase();

// create the Grid
const createGrid = (size) => {
  let row = 0;
  let col = 0;
  for (row = 0; row < size; row++) {
    grid[row] = [];
    for (col = 0; col < letters.length; col++) {
      // instead of grid[row][col] = `${letters[row]}${col + 1}`;
      grid[row][col] = `${letters[col]}${row + 1}`;
    }
  }
};

createGrid(letters.length);
console.log(grid);

3 Comments

Thanks, Ran, but what about if I want to keep both results, like 2 different multidimensional arrays, one will be the cols and one will be the rows.
To be more specific; the first grid will be [['A1', 'A2'...], ['B1', 'B2'...]] and the second one will be [['A1', 'B1'...], ['A2', 'B2'...]]
In this case you can have two grid variables. in the same iteration you can assign them both (one like you did and the second one like I showed you)

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.