2015-12-02 33 views
0

如何可以简化阵列组织/组基于条件的阵列 - 的JavaScript

[ china, country1(city1), country1(city2), country1(city3)), korea, australia]

[ china, country1(city1, city2, city3), korea, australia] 
+0

变化'country1'接受多个参数?当然,这也会改变数组中元素的数量。 –

+0

country1中的元素数量可能不同。如何更改country1以接受参数?我认为这只是一个数组元素。 – Mustang

+0

'country1'似乎是一个函数。情况并非如此吗?你的问题根本不清楚。请相应阅读[问]并[编辑]你的问题。 –

回答

0

迭代通过数组元素

  1. 提取国家和城市分别
  2. 更新国家城市地图(您的对象可以跟踪映射到哪个城市的国家)
  3. 通过此对象的键,并与您的国家城市创建一个新的阵列。如果该国家有城市阵列,请使用join(',')获取逗号分隔的城市字符串。

var cityRegex = /\((.*)\)/; 
 
var countryRegex = /([^()]*)\(?.*\)?/; 
 

 
var countryCityArray = ['china', 'country1(city1)', 'country1(city2)', 'country1(city3)', 'korea', 'australia']; 
 

 
var countryCityMap = {}; 
 

 
countryCityArray.forEach(function(countryCity) { 
 
    var matches = countryRegex.exec(countryCity); 
 
    var country = matches[1] 
 
    if (!countryCityMap[country]) { 
 
    countryCityMap[country] = []; 
 
    } 
 

 
    matches = cityRegex.exec(countryCity); 
 

 
    if (matches && matches.length) { 
 
    var city = matches[1]; 
 
    countryCityMap[country].push(city); 
 
    } 
 

 
}); 
 

 
var targetArray = Object.keys(countryCityMap).map(function(country) { 
 
    var countryCity = country; 
 
    if (countryCityMap[country].length) { 
 
    countryCity = countryCity + '(' + countryCityMap[country].join(',') + ')'; 
 
    } 
 
    return countryCity; 
 
}); 
 

 
console.log(targetArray);

+0

我试过了。如果数组元素具有其他特殊字符,解决方案不起作用:var array = ['abc','xyz(test2)','x&z(test3)','x&z(test4)','pqr','kl -m']; – Mustang

+0

@SAM,正则表达式必须修改。看到我更新的答案 – AmmarCSE