how to create nxn matrix/array in javascript?

An ES6 solution using Array.from and Array#fill methods.

function matrix(m, n) {
  return Array.from({
    // generate array of length m
    length: m
    // inside map function generate array of size n
    // and fill it with `0`
  }, () => new Array(n).fill(0));
};

console.log(matrix(3,2));


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

For enhanced readability

const create = (amount) => new Array(amount).fill(0);
const matrix = (rows, cols) => create(cols).map((o, i) => create(rows))

console.log(matrix(2,5))

For less code

const matrix = (rows, cols) => new Array(cols).fill(0).map((o, i) => new Array(rows).fill(0))

console.log(matrix(2,5))

Tags:

Javascript