Would like to create a two dimensional m x n array in javascript, based on the number of columns, that is inputed as an argument in my function, the rows would be created from another argument which would be an array.
What I look to achieve - Desired Result:
var arr = [0,1,2,3,4,5,6,7,8,9]
function TwoDimensionalArray(numRows, numCols) {
//Magic happens here!
}
TwoDimensionalArray(arr, 4);
As you can see the is a 3 x 4 matrix below and a desired result
[[0,1,2,3], [4,5,6,7],[8,9]]
The input size doesn't make the difference, the number of columns is the key factor and the determinant factor.
What I have currently - Not Desired Result:
var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
function TwoDimensionalArray(numRows, numColumns) {
var twoD = [];
for (var row = 0; row < numRows.length; ++row) {
var cardIndex = numRows[row]
// console.log(numRows[row]);
var columns = [];
for(var j =0; j < numColumns; ++j) {
columns[j] = cardIndex;
}
twoD[cardIndex] = columns;
}
return twoD;
};
var matrixTwoD = TwoDimensionalArray(arr, 4);
console.log(matrixTwoD);
console.log(matrixTwoD[0][0]);
console.log(matrixTwoD[0][1]);
console.log(matrixTwoD[0][2]);
console.log(matrixTwoD[0][3]);
My current code creates an array that repeats each of the elements 4 times each until the number 13 with a column size of 4: [[0,0,0,0], [1,1,1,1]....[13,13,13,13]]
Maybe am doing something wrong in my for loop or not approaching the problem correctly. But anything to point me in the right direction to get the above desire result.
Bouns
Also would anyone also be kinda to point me to additional resources for matrix algebra pertaining to this sort of problem and anything in general that would help for self study.
Thanks a bunch!