There are several ways you could approach this issue:
Using concat() and 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()); // Another option is to use innerArrSrc.slice();
}
Array.prototype.concat() and Array.prototype.slice() both provide a shallow copy of the original array.
Representing as a one-dimensional array
Alternatively, you can represent your matrix as a one-dimensional array and create 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 for accessing a specific index in the matrix represented this way might look like:
function getMatrixIndex(myMatrix, col, row, numCols) {
var index = row * numCols + col;
return myMatrix[index];
}
Utilizing Array.prototype.fill
If you want to make use of ES6 features, Array.prototype.fill could be helpful:
// 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);
Performance Testing with jsPerf
You can conduct tests using this jsPerf test to determine the fastest method. The tests were run on various browsers and platforms, including:
- 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