I have a flat array like this
['-', '-', '-', '-', '-', '-', '-', '-', '-']
and I want to convert it to be 2D like this
[
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']
]
I saw this question but it is in javascript and I am getting error on declaring types of the "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);
2
Answers
TypeScript is giving you an error because it can’t figure out the type of the matrix variable.
code:
Output:
Glad to answer your question.
I have found some errors in your code.
In your code, you’ve declared the list parameter as an array of numbers ( number[] ), but you’re passing in an array of strings ( [‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘, ‘-‘] ). To fix this, you should update the type declaration for list to be an array of strings ( string[] ).
Here’s the updated code:
Hope this would help you.