Javascript过滤器数组在单独的数组中

时间:2017-01-01 21:50:02

标签: javascript arrays

我有一个数组,在数组中每个id都有一个像region or province or location or city这样的文本,它的字符串如下所示:

 ["region43","region63","location23","region86","location63","province25","province12","city64","city98","province90"]

如何在没有文字和字符串的4个单独数组中过滤它:

对于省文本数组应该是:

  [25,12,90]

对于城市文本数组应该是:

  [64,98]

对于位置文本数组应该是:

 [23,63]

对于区域文本数组应该是:

  [43,63,86]

2 个答案:

答案 0 :(得分:3)

您可以使用正则表达式并将字符串拆分为非数字和数字部分。结果,我建议使用一个对象进行收集。稍后,您可以使用分配,例如

region = result.region;

表示单一类型。



var data = ["region43", "region63", "location23", "region86", "location63", "province25", "province12", "city64", "city98", "province90"],
    result = Object.create(null);

data.forEach(function (a) {
    var m = a.match(/(\D+)(\d+)/);
    result[m[1]] = result[m[1]] || [];
    result[m[1]].push(m[2]);
});

console.log(result);

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




答案 1 :(得分:1)

您可以像这样使用mapreduce

var data = ["region43","region63","location23","region86","location63","province25","province12","city64","city98","province90"];

var result = data.map( s => s.split(/(\d+)/) )
      .reduce ( (o, [key,val]) => (o[key] = (o[key] || []).concat(+val), o), {} );

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

您可以按如下方式获取其中一个数组:

result['province'] // [25,12,90]