0

I have an array that looks like this

    $scope.A = [

          [ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
          [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]

        ];

I want to make it into something like this

        $scope.B = [
           [
             [1.31069258855609,103.848649478524], [1.31138534529796,103.848923050526]
           ],
           [
             [1.31213221536436,103.848328363879], [1.31288473199114,103.849575392632]
           ]
         ];

PS: Sorry if this isnt splitting, I am not sure how to address this problem as

Code:

    var latlngs = $scope.polyLineCord.map(subarr => subarr.map(str => str.split(',').map(Number)))
    console.log(latlngs)

enter image description here

3
  • Fetched from an api Commented Nov 8, 2018 at 9:16
  • I am trying to plot a polyline in my map Commented Nov 8, 2018 at 9:17
  • Ohh, sorry it was a typo edited it Commented Nov 8, 2018 at 9:18

2 Answers 2

1

map each item in the outer array, then .map each subarray and split by commas, and map again by Number to transform the strings to numbers:

const input = [
  ["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
  ["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
console.log(
  input.map(
    subarr => subarr.map(
      str => str.split(',').map(Number)
    )
  )
);

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

8 Comments

I have no idea how to read this, is it possible to store the result into a variable?
Just put something like var somevar = in place of console.log(, the console.log in the code above is just to demonstrate that it results in the output you want
Nice! Exactly how i want it. Thanks again for the help!
are you still there? I don't know why but I am return with a different result when I use it on my code
The result I am returned is nested in an array
|
0

A function to do the job:

function splitMyArray(arr) {
    for (var i = 0; i < arr.length; ++i) {
        var line = arr[i];
        for (var k = 0; k < line.length; ++k) {
            var parts = line[k].split(',');
            line[k] = [parseFloat(parts[0]), parseFloat(parts[1])];
        }
    }
    return arr;
}

Usage example:

var myArr = [
    ["1.31,103.84", "1.32,103.85"],
    ["1.39,103.77", "1.40,103.78"]
];

var splitted = splitMyArray(myArr);
console.log(splitted);

Comments

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.