0

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]

darkertime
  • 33
  • 1
  • 6

4 Answers4

1

You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).

let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);

Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :

let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);

Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.

Pac0
  • 21,465
  • 8
  • 65
  • 74
1

The first step would be to create valid JSON from your string.

If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.

A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":

const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";

// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]"; 

// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);

// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);

// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
Sam Bokai
  • 538
  • 1
  • 5
  • 13
0

This thread shows you how to loop through an array of strings to convert it to an array of floats.

  • Please explain it in a few words here. – arashka Jul 30 '18 at 10:12
  • links only answer are not usually considered valid answer on SO. If you think the question is already answered in the linked question you suggested, consider flagging the question as duplicate (click 'flag' under question, copy link in the search bar) – Pac0 Jul 30 '18 at 11:53
  • Good to know I will do! – Tyler Potts Jul 30 '18 at 13:02
0

i hope this will work..

var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]

var output = [];
  input.forEach(o => {
    o.forEach(s => parseFloat(s))
    output.push(o);
})

console.log(output);
Learner
  • 8,379
  • 7
  • 44
  • 82