Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create arrays inside array from string in JavaScript

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading