ITnyp
ITnyp

Reputation: 107

Javascript: how to split nested array of strings to numbers

I have an array that looks like this

var a = [ 

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

    ];

I want to split that into

var b = [ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ]

var c =  [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]

And further into

var d = [ 1.31069258855609, 1.31213221536436, 1.31213221536436, 1.31288473199114 ]
var e = [ 103.848649478524, 103.848923050526, 103.848328363879, 103.849575392632 ]

How can I do that? I tried using things like

.split(',')[0]
.split(',')[1]

But there is comma after the " ". Can someone help me out here? Please and thanks!

Upvotes: 3

Views: 2739

Answers (5)

Dacre Denny
Dacre Denny

Reputation: 30360

One approach to this problem would be to take advantage of the ordering of number values in your string arrays.

First flatten the two arrays into a single array, and then reduce the result - per iteration of the reduce operation, split a string by , into it's two parts, and then put the number value for each part into the output array based on that values split index:

var a = [ 
  [ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
  [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];

const result = a.flat().reduce((output, string) => {
  
  string.split(',')   // Split any string of array item 
  .map(Number)        // Convert each string to number
  .forEach((item, index) => {  
    output[index].push(item)  // Map each number to corresponding output subarray
  })
  
  return output
  
}, [[],[]]) 

const [ d, e ] = result

console.log( 'd = ', d )
console.log( 'e = ', e )

Upvotes: 1

slider
slider

Reputation: 12990

Here's another solution using map, flat and reduce. The idea is to get one continuous array of all the numbers and then add alternating numbers to 2 different arrays using reduce:

const a = [
  ["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
  ["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];

const [d, e] = a.map(arr => arr.map(s => s.split(',').map(s => parseFloat(s))))
                .flat(2)
                .reduce((acc, curr, i) => {
                  acc[i % 2].push(curr);
                  return acc;
                }, [[], []]);
           
console.log(d);
console.log(e);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370699

You can reduce into an array, iterating over each subarray, and then over each split number from the subarray items:

const a = [
  ["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
  ["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
const [d, e] = a.reduce((a, arr) => {
  arr.forEach((item) => {
    item.split(',').map(Number).forEach((num, i) => {
      if (!a[i]) a[i] = [];
      a[i].push(num);
    });
  });
  return a;
}, []);
console.log(d);
console.log(e);

Upvotes: 1

dotconnor
dotconnor

Reputation: 1786

Heres a quick and dirty way of doing, basically recursively look through the array until you find a string, once you have one split it at the comma, then add the results to two different arrays. Finally, return the two arrays.

var a = [ 
    [ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
    [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]
];

function sort(array) {
  var a = [], b = [];
  function inner(c) {
    c.forEach(function (d) {
      if (Array.isArray(d)) {
        inner(d);
      } else {
        var e = d.split(',');
        a.push(e[0]);
        b.push(e[1]);
      }
    })
  }
  inner(array);
  return [a,b]
}
console.log(sort(a));

Upvotes: 1

Vishu Bhardwaj
Vishu Bhardwaj

Reputation: 321

Please check if the following code matches your requirement.

function test3(a) {
 let result = [];
 for (let i=0; i<a.length; i++) {
  let subArr = [];
  for (let j=0; j<a[i].length; j++) {
   let splits = a[i][j].split(',');
   subArr.push(splits[0]);
   subArr.push(splits[1]);
  }
  result.push(subArr);
 }
 console.log("Result ", result);
 return result;
}

Then call the following code :

var a = [[ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ], [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]];
var b = a[0]
var c = a[1]
var d = test3(a)[0]
var e = test3(a)[1]

Upvotes: 0

Related Questions