Ma6139735 Ma6139735 - 2 months ago 18
Javascript Question

how to create nxn matrix/array in javascript?

I want to create a array or matrix with non fixed number of rows like



var matrix=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]


how can i do that?

Answer

you can alse use the code like:

function matrix(m, n) {
    var result = []
    for(var i = 0; i < n; i++) {
        result.push(new Array(m).fill(0))
    }
    return result
}
console.log(matrix(2,5))