ITnyp
ITnyp

Reputation: 107

Angularjs split array

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

Upvotes: 0

Views: 47

Answers (2)

rodrigocfd
rodrigocfd

Reputation: 8013

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);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370609

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)
    )
  )
);

Upvotes: 1

Related Questions