JavaScript: How to write a function that accepts two arguments(numbers) that produces a grid?

Write a function makeGrid that accepts two arguments:

numColumns (number) – how many columns we want our grid to have

numRows (number) – how many rows we want our grid to have

makeGrid should return a two-dimensional array that represents a grid of the given dimensions.

What i did:

function makeGrid(numColumns, numRows){
    const arrayX = []
    const arrayY = []
    for (let i=1; i<=numColumns; i++){
        arrayX.push(numColumns[i])
    }
    for(let j=1; j<=numRows; j++){
        arrayY.push(arrayX)
    }
    return arrayY
}
result = makeGrid(2,3)
console.log(result)

I was expecting: [[1,2],[1,2],[1,2]]

What I got: [[undefined],[undefined],[undefined]]

>Solution :

Use Nested Loops :

function makeGrid(numColumns, numRows){
    const result = [];
    for (let i=1; i<=numRows; i++){
      result[i-1] = [];
      for(let j=1; j<=numColumns; j++){
        result[i-1][j-1] = j;
      }    
    }
    
    return result;
}
result = makeGrid(2,3)
console.log(result)

Leave a Reply