Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create nxn matrix/array in javascript?

Tags:

javascript

I want to create an 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?

like image 289
Madhav Avatar asked Aug 31 '16 06:08

Madhav


2 Answers

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));
like image 115
Pranav C Balan Avatar answered Sep 28 '22 02:09

Pranav C Balan


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))
like image 43
marchen Avatar answered Sep 28 '22 03:09

marchen