I have strings like this :
- "831,403,746,399,745,409,752,426,764,435,775,448,781,467,780,483,776,509,826,513"
- "832,402,917,408,915,422,910,432,904,437,894,443,885,450,878,462,876,475,874,491,874,516,825,511"
- "468,297.00000762939453,434,218.00000762939453,416,230.00000762939453,409,246.00000762939453,405,264.00000762939453,400,275.00000762939453,384,282.00000762939453,374,288.00000762939453,352,297.00000762939453,369,340.00000762939453"
... and so on.
I need to format the strings and produce arrays in array like this :
E.g.:
var myArray = [
[831,403],
[746,399],
[745,409],
[752,426],
[764,435],
[775,448],
[781,467],
[780,483],
[776,509],
[826,513],
];
It is possible and how? Thanks in advance!
CodePudding user response:
function parseToMatrix(str, rowCount = 2) {
let numbers_array = str.split(",").map((str) => parseFloat(str));
let matrix = [];
for (let i = 0; i < numbers_array.length; i = rowCount) {
matrix.push(numbers_array.slice(i, i rowCount));
}
return matrix;
}
let str =
"831,403,746,399,745,409,752,426,764,435,775,448,781,467,780,483,776,509,826,513";
console.log(parseToMatrix(str));