Search code examples
angulartypescriptturfjs

How to convert an Array of Arrays of strings to an Array of Arrays of numbers?


I have an Array of Arrays of strings like below:

 [    
 0: Array(1)
    0: Array(6)
        0:  [5.379856, 43.252967]
        1:  [5.422988, 43.249466]
        2:  [5.425048, 43.245153]
        3:  [5.383804, 43.239838]
        4:  [5.399856, 43.212967]
        5:  [5.379856, 43.252967]
1: Array(1)
    0: Array(6)
        0:  [5.39014, 43.279295]
        1:  [5.393069, 43.279249]
        2:  [5.391814, 43.278421]
        3:  [5.390709, 43.278749]
        4:  [5.3909, 43.2785]
        5:  [5.39014, 43.279295]
 ]

The values are strings. I would like to convert each value into a number. Can someone explain how can this be done without a loop please?

Kind Regards,


Solution

  • You have numbers in the array not strings. But if you have strings, you can use map() and Number() to convert them to numbers.

    var data = [
      [
        ["5.379856", "43.252967"],
        ["5.422988", "43.249466"],
        ["5.425048", "43.245153"],
        ["5.383804", "43.239838"],
        ["5.399856", "43.212967"],
        ["5.379856", "43.252967"]
      ],
      [
        ["5.39014", "43.279295"],
        ["5.393069", "43.279249"],
        ["5.391814", "43.278421"],
        ["5.390709", "43.278749"],
        ["5.3909", "43.2785"],
        ["5.39014", "43.279295"]
      ]
    ];
    
    data = data.map(arr => arr.map(item => item.map(value => Number(value))));
    
    console.log(data);