最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Split array into multiple array's or alternate - Javascript - Stack Overflow

programmeradmin2浏览0评论

I have an array

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

The oute 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

I have an array

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

The oute 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

Share Improve this question asked Feb 21, 2013 at 9:34 MachMach 672 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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);

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];
}

Basically you should iterate over the array and for each item you split the string into two parts, based on the ma. 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]);
}
发布评论

评论列表(0)

  1. 暂无评论