Mahmud Adam
Mahmud Adam

Reputation: 3579

Populating a multidimensional array with user input

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.

Upvotes: 0

Views: 1761

Answers (3)

Abdullah Razzaki
Abdullah Razzaki

Reputation: 992

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

Upvotes: 1

Aman Rawat
Aman Rawat

Reputation: 2625

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

Upvotes: 1

Josh
Josh

Reputation: 4806

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' ] ] ]

Upvotes: 1

Related Questions