Jimmy
Jimmy

Reputation: 925

Javascript - String to Coordinates Array

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/

Upvotes: 1

Views: 2177

Answers (2)

Igor Raush
Igor Raush

Reputation: 15240

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.

Upvotes: 3

tadman
tadman

Reputation: 211560

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.

Upvotes: 1

Related Questions