Reputation: 67
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
Upvotes: 2
Views: 2552
Reputation: 11302
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];
}
Upvotes: 3
Reputation: 173562
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]);
}
Upvotes: 1
Reputation: 145398
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);
Upvotes: 3