There are a couple of approaches you could take:
concat()/slice()
var numCols = 4;
var numRows = 4;
var innerArrSrc = [];
var outerArr = [];
for (var i = 0; i < numCols; i++) {
innerArrSrc.push(0);
}
for (var j = 0; j < numRows; j++) {
outerArr.push(innerArrSrc.concat()); // Could also use innerArrSrc.slice();
}
Both Array.prototype.concat()
and Array.prototype.slice()
will return a shallow copy of the source array.
one-dimensional array
Alternatively, you could represent your matrix as an one-dimensional array rather than a multi-dimensional one and provide functions to access specific indexes based on row-column values:
var numRows = 4;
var numCols = 4;
var len = numRows * numCols;
var outerArr = [];
for (var i = 0; i < len; i++) {
outerArr.push(0);
}
A function to access a specific index of a matrix represented this way might look like:
function getMatrixIndex(myMatrix, col, row, numCols) {
var index = row * numCols + col;
return myMatrix[index];
}
Array.prototype.fill
If you want to take advantage of new ES6 features Array.prototype.fill
should suit your needs:
// Multi-dimensional
var numRows = 4;
var numCols = 4;
var outerArr = new Array(row_count).fill(new Array(column_count).fill(0)).map(a => a.slice());
// Or one-dimensional
var len = numRows * numCols;
var oneDim = new Array(row_count * column_count).fill(0);
jsPerf tests
You can run this jsPerf test to see which is fastest. I've tested in:
- Firefox 42.0 32-bit on Windows NT 10.0 64-bit
- Chrome 44.0.2403.130 32-bit on Windows NT 10.0 64-bit
- Chrome 47.0.2526.73 32-bit on Windows NT 10.0 64-bit
- Android Browser 42.0 (Gecko) on Android 6.0