[SOLVED] How can I make a JavaScript function that takes two arguments (numRows, numColumns), and returns a 2D array with the correct grid values?

Issue

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.

`makeGrid(3,4);
  /* => [[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]]
   */`

I’ve tried multiple variations of the same code below, both complicated and simpler with the same results. It returns a grid with the correct number of columns and the correct number of rows, but it keeps returning the wrong cell values. I am beyond confused at this point so any other insight or depth into what I’m missing would be greatly appreciated!

`function makeGrid(numColumns, numRows){
  arr = [];
  for (let i = 0; i < numRows; i++){
    arr[i] = [];
    for (let j = 0; j < numColumns; j++){
      arr[i].push(j)
    }
  }return arr;
}`

Solution

Try pushing j+1 to the arr array eg. arr[i].push(j+1).

Working code:

function makeGrid(numColumns, numRows) {
  arr = [];
  for (let i = 0; i < numRows; i++) {
    arr[i] = [];
    for (let j = 0; j < numColumns; j++) {
      arr[i].push(j + 1)
    }
  }
  return arr;
}

console.log(makeGrid(3, 4))

Answered By – Ankit Saxena

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *