6

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?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Madhav
  • 559
  • 2
  • 11
  • 34
  • 1
    Possible duplicate of [Matrix of numbers javascript](http://stackoverflow.com/questions/38016201/matrix-of-numbers-javascript) – str Aug 31 '16 at 06:36
  • What is stopping you from just doing it as you already wrote it? See [here](http://stackoverflow.com/a/966234/1063673) for multi dimensional array access. – Steffen Harbich Aug 31 '16 at 06:42

6 Answers6

13

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));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
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))
marchen
  • 46
  • 1
  • 7
2

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))
techmsi
  • 433
  • 1
  • 5
  • 21
0

I use the following ES5 code:

var a = "123456".split("");
var b = "abcd".split("");
var A = a.length;
var B = b.length;

var t= new Array(A*B);
for (i=0;i<t.length;i++) {t[i]=[[],[]];} 

t.map(function(x,y) {
   x[0] = a[parseInt(y/B)];
   x[1] = b[parseInt(y%B)];
  });    
t;

It returns a 2d array and obviously your input doesn't have to be strings.

For some amazing answers in ES6 and other languages check out my question in stack exchange, ppcg.

alexandros84
  • 321
  • 4
  • 14
0
function createArray(row, col) {
  let matrix = [];
  for (let i = 0; i < row; i++) {
    matrix.push([]);
    for (let j = 0; j < col; j++) {
      matrix[i].push([]);
    }
  }
  console.log(matrix);
}

createArray(2, 3);

OUTPUT:- [ [ [], [], [] ], [ [], [], [] ] ]

note: if you want to get array with values, like [ [ [1], [1], [1] ], [ [1], [1], [1] ] ] then replace 6th line of code with matrix[i].push([1]);

-1

Can be done like this:

Array(n).fill(Array(m).fill(0))

where

n - number of rows
m - number of columns
Lady Dev
  • 7
  • 2