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?
-
1Possible duplicate of Matrix of numbers javascriptstr– str2016年08月31日 06:36:10 +00:00Commented 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.Steffen Harbich– Steffen Harbich2016年08月31日 06:42:16 +00:00Commented Aug 31, 2016 at 6:42
6 Answers 6
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));
Comments
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
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
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
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
Can be done like this:
Array(n).fill(Array(m).fill(0))
where
n - number of rows
m - number of columns