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?

2
  • 1
    Possible duplicate of Matrix of numbers javascript Commented Aug 31, 2016 at 6:36
  • What is stopping you from just doing it as you already wrote it? See here for multi dimensional array access. Commented Aug 31, 2016 at 6:42

6 Answers 6

16

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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

1 Comment

is it possible to get same result without using .fill() ?
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.

Comments

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

Comments

-1

Can be done like this:

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

where

n - number of rows
m - number of columns

2 Comments

Each row will reference the same object! That's probably isn't desired
right, see what happens if you declare e.g. 5x5 matrix this way and then set a[2][3] = 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.