Reputation: 569
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?
Upvotes: 6
Views: 18392
Reputation:
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]);
Upvotes: 0
Reputation: 7
Can be done like this:
Array(n).fill(Array(m).fill(0))
where
n - number of rows
m - number of columns
Upvotes: -1
Reputation: 443
const create = (amount) => new Array(amount).fill(0);
const matrix = (rows, cols) => create(cols).map((o, i) => create(rows))
console.log(matrix(2,5))
const matrix = (rows, cols) => new Array(cols).fill(0).map((o, i) => new Array(rows).fill(0))
console.log(matrix(2,5))
Upvotes: 3
Reputation: 337
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.
Upvotes: 0
Reputation: 115212
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));
Upvotes: 16
Reputation: 46
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))
Upvotes: 2