2

I have an array

var array = ['123.456789,123.1','456.7890123,234.1','789.0123456,345.1'];

The outcome I'm looking for is

var array1 = [123.456789,456.7890123,789.0123456];
var array2 = [123.1,234.1,345.1];

What's best practice for doing this? I've been looking at .split(""); but would like to know the best way to approach it.

Thanks in advance Mach

3 Answers 3

3
var arr = ["123.456789,123.1","456.7890123,234.1","789.0123456,345.1"];

var array1 = [],
    array2 = arr.map(function(e) {
        e = e.split(",");
        array1.push(+e[0]);
        return +e[1];
    });

console.log(array1, array2);
Sign up to request clarification or add additional context in comments.

2 Comments

why the plus sign in +e[0]? Is it the same as a cast?
@letiagoalves Yep, it's a shorcut for Number(e[0]).
3

I think that you should go with split function. Try this or see this DEMO:

var array = ['123.456789,123.1','456.7890123,234.1','789.0123456,345.1'];
var array1 = [], array2 = [];

for(var i=0; i<array.length; i++){
   array1[i] = array[i].split(",")[0];
   array2[i] = array[i].split(",")[1];
}

3 Comments

@Jack what do you sugest? for(var i=0; i<array.length; i++) style?
Yep, that would be better :) you can also cache the array length in a local variable (micro optimization though).
1

Basically you should iterate over the array and for each item you split the string into two parts, based on the comma. Each part goes into their respective array.

If Array.forEach() is allowed:

var a1 = [], a2 = [];

array.forEach(function(item) {
  var parts = item.split(',');
  a1.push(+parts[0]);
  a2.push(+parts[1]);
}

Otherwise:

var a1 = [], a2 = [];

for (var i = 0, item; item = array[i]; ++i) {
  var parts = item.split(',');
  a1.push(+parts[0]);
  a2.push(+parts[1]);
}

2 Comments

In your case it is better to use Array.forEach.
@VisioN Don't remember using that before ... ah yes, that's a lot better :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.