Iterate through multidimensional array javascript

Viewed 55

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);

2 Answers

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));

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);

Related