I need help transforming a flat array into a 2D array, like this:
['-', '-', '-', '-', '-', '-', '-', '-', '-']
My desired output is:
[
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']
]
While researching, I came across this helpful question. However, it's in javascript and I encountered an error when trying to declare the types for "list" and "elementsPerSubArray."
// declaring type of list and elementsPerSubArray
function listToMatrix(list: number[], elementsPerSubArray: number) {
var matrix = [], i, k;
for (i = 0, k = -1; i < list.length; i++) {
if (i % elementsPerSubArray === 0) {
k++;
matrix[k] = [];
}
// here I am facing error says " Argument of type 'number' is not assignable to parameter of type 'never' "
matrix[k].push(list[i]);
}
return matrix;
}
var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3);