2017-10-13 72 views
0

我有阵列以这种形式如何使用JavaScript动态创建数组?

['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297','203,548', '204,548', '204,548' ] 

欲望输出:

0:['203,448', '204,448', '230,448','24,448', ] 
1: [ '204,297', '205,297', '231,297', '24,297'] 
2: ['203,548', '204,548', '204,548'] 

欲sepreate的2 featur 即203底座上的元件, 和204

+0

什么你试过吗? –

+0

我尝试不同使用第二个功能 foreach功能layer_featureinfo if features_result [1] == 297: else if features_result [1] == 448 –

+0

这是哪种语言? :) – Gautam

回答

1

您可以为该字符串的相同第二部分取一个散列表,并在一个阵列。

var data = ['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297', '203,548', '204,548', '204,548'], 
 
    hash = Object.create(null), 
 
    result = data.reduce(function (r, a) { 
 
     var key = a.split(',')[1]; 
 
     if (!hash[key]) { 
 
      hash[key] = []; 
 
      r.push(hash[key]); 
 
     } 
 
     hash[key].push(a); 
 
     return r; 
 
    }, []); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

对于只把第一部分,你可以使用分裂阵列

var data = ['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297', '203,548', '204,548', '204,548'], 
 
    hash = Object.create(null), 
 
    result = data.reduce(function (r, a) { 
 
     var s = a.split(','); 
 
     if (!hash[s[1]]) { 
 
      hash[s[1]] = []; 
 
      r.push(hash[s[1]]); 
 
     } 
 
     hash[s[1]].push(s[0]); 
 
     return r; 
 
    }, []); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

非常感谢你能引导让说,如果我们想 结果持有[ [ “203”, “204”, “230”, “ 24" ], [ “204”, “205”, “231”, “24” ], [ “203”, “204”, “204” ] ] 我尝试,但我不工作,我可能在其他一些情况下使用 –

+0

Mine Pleasure Mam&是的,我发现相同只是1分钟前谢谢 –