1

I'm new to Javascript and i'm having some issues converting a string to an array of coordinates values .

This is my string (Temporary - the string might have more/less coordinates) :

var str = "12:13.94:13:14.9:";

each coordinate are separated by a ":" , where

str[0] = x1;
str[1] = y1;
str[2] = x2;
str[3] = y2;
.................

I want it to return a 2D array of coordinates as :

var cArray = [[12,13.94],[13,14.9].........];

Is there any way to do this ?

I tried :

var cString = coorStr.split(":");

But it just returns an array of string,

This is what i have so far : https://jsfiddle.net/mLskwxyj/

3
  • var cArray = [cString.slice(0, 2), cString.slice(2, 4)]? There is no single function to do what you want. Commented Feb 25, 2016 at 21:32
  • JSON.parse("["+"12:13.94:13:14.9:".replace(/([\d\.]+):([\d\.]+)/g,"[$1,$2]").replace(":",",").slice(0,-1)+"]") Commented Feb 25, 2016 at 21:51
  • stackoverflow.com/questions/4492385/… Commented Feb 25, 2016 at 21:51

2 Answers 2

3

tadman's answer gives a way to parse your string into an array of numbers:

var str = '12:13,94:13:14,9';
var num = str.split(':').map(Number);

For a generic way to split this array into [x, y] pairs, this answer provides a terse solution. I've slightly modified it below (to remove the Lodash dependency):

var coords = num.reduce(function (r, v, i, a) {
  // on every even element, grab a pair of numbers and 
  // add to the result
  if (i % 2 === 0)
    r.push(a.slice(i, i + 2));

  return r;
}, []);

Here is a working example. Note that a for loop with a pre-allocated result array will be more performant. I just wanted to provide a way to do it in a single statement.

Sign up to request clarification or add additional context in comments.

Comments

1

This is a bit clunky but arranges them as you want:

var str = "12:13,94:13:14,9:";

var split = str.replace(/,/g, '.').split(':').map(Number);

var result = [
  [ split[0], split[1] ],
  [ split[2], split[3] ],
];

console.log(result);
// [ [ 12, 13.94 ], [ 13, 14.9 ] ]

Accounts for the European style use of , in numbers.

Update: Added .map(Number) as suggested.

7 Comments

you might want to add a .map(Number)
Yeah, did it a more hack way, but fixed now. Great call. Thanks!
@tadman - will this work in a for loop in the event where the string has more coordinates
@Jimmy: Of course not. If you need a loop, use a loop instead of the array literal. See this question (and those linked from there) for generic solutions of all kinds.
Is there an example for the for loop code . I'm trying in js.do but getting error in my forloop for(int i = 0 ; i<split.length ; i++) { }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.