I have an array of geodata stored as a string, and need to turn into into a array of numbers.
var input = "[34.1103897,-118.0398531]"
var output = [34.1103897,-118.0398531]
Not sure the best way to do this. Any tips/ suggestions appreciated!
I have an array of geodata stored as a string, and need to turn into into a array of numbers.
var input = "[34.1103897,-118.0398531]"
var output = [34.1103897,-118.0398531]
Not sure the best way to do this. Any tips/ suggestions appreciated!
The easiest way to convert an array of that format is to use JSON.parse
.
Simply:
var input = "[34.1103897,-118.0398531]";
var output = JSON.parse(input);
Assuming the data is always formatted with no whitespace, you could simply remove the first and last characters, and split on ',':
var input = '[34.1303897,-118.0398591]';
var output = input.slice(1, -1).split(',').map(parseFloat);
Alternatively, that syntax is technically valid JSON syntax, so you could just:
var input = '[34.1303897,-118.0398591]';
var output = JSON.parse(input);
However, this could be dangerous depending on where the data comes from.
JSON.parse is the obvious choice, but there is also manual parsing with a regular expression (the following assumes you might also want to match a leading '+'):
var input = "[34.1103897,-118.0398531]"
var output = (input.match(/[+-]?[\d\.]+/g) || []).map(Number);
console.log(output)
You might consider validating the input or the resulting output regardless of the method chosen to convert it to an array.