如何简化数组
[ china, country1(city1), country1(city2), country1(city3)), korea, australia]
到
[ china, country1(city1, city2, city3), korea, australia]
答案 0 :(得分:0)
遍历数组元素
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);