Mahmud Adam Mahmud Adam - 3 months ago 12
Javascript Question

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
.

Answer

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

Comments