0

I am trying to fill a multidimensional array with user input. I have this function:

var buildIt = function(row, col){
 var a = []
 var input
  for(var i = 0; i < row; i++){
    a[i] = []
    input = prompt('Input: ')
    for(var j = 0; j < col; j++){
      a[i][j] = input.split('')
    }
  }
return a
}

window.buildIt(3,3)

I want to make it so that the user is prompted the number of times there are rows. If user creates a matrix with three rows, the user should be prompted for input three times. I want to store this input in each row. For example, user enters foo bar baz array a should like this:

a = [
  ['f','o','o'],
  ['b','a','r],
  ['b','a','z]
 ]

When I call the function:

var board = buildIt(3,3)
console.log(board[0][0])

It logs all the elements in the first row instead of the element at point [0][0] which should be f if user entered foo.

1
  • 1
    3x3 is 9. You are looping more than you expect Commented Aug 19, 2016 at 15:31

3 Answers 3

1

You are using prompt inside the two loops so if you have a metrix of 3x3 then it will prompt you 9 times to insert the data so i removed the extra loop. Try this

    var buildIt = function(row, col){
    var a = []
    var input
    for(var i = 0; i < row; i++){
    	input = prompt('Input: ')
    	a[i] = input.split('')
    }
    return a
    }
    
    console.log(window.buildIt(3,3));

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

Comments

1

The code you posted works and the output is given below (I substituted a random string for the input). However, your array should actually look like this afterward, as you are one level too shallow in your example (remember that a[i][j] is assigned the result of .split(''), which returns an array of characters in this case, so there will exist an a[i][j][0] which will be a character.

> buildIt(3,3)
[ [ [ 'G', 'C', 'T', 'J', 'O' ],
    [ 'S', 'Q', 'S', 'B', 'G' ],
    [ 'D', 'E', 'U', 'P', 'Y' ] ],
  [ [ 'D', 'B', 'I', 'Z', 'Q' ],
    [ 'G', 'M', 'U', 'N', 'R' ],
    [ 'D', 'T', 'I', 'A', 'V' ] ],
  [ [ 'J', 'L', 'O', 'H', 'V' ],
    [ 'U', 'C', 'D', 'B', 'H' ],
    [ 'U', 'C', 'X', 'E', 'W' ] ] ]

Comments

1

You don't need to pass the no of columns, just the rows and remove the inner loop because you only need to execute the code for the number of rows. The updated code

    var buildIt = function(row){
    var a = []
    var input
    for(var i = 0; i < row; i++){
       input = prompt('Input: ');
       a[i] = input.split('');
    }
    return a;
    }
    buildIt(3);

Comments

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.