Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading