如何可以简化阵列组织/组基于条件的阵列 - 的JavaScript
[ china, country1(city1), country1(city2), country1(city3)), korea, australia]
到
[ china, country1(city1, city2, city3), korea, australia]
如何可以简化阵列组织/组基于条件的阵列 - 的JavaScript
[ china, country1(city1), country1(city2), country1(city3)), korea, australia]
到
[ china, country1(city1, city2, city3), korea, australia]
迭代通过数组元素
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);
变化'country1'接受多个参数?当然,这也会改变数组中元素的数量。 –
country1中的元素数量可能不同。如何更改country1以接受参数?我认为这只是一个数组元素。 – Mustang
'country1'似乎是一个函数。情况并非如此吗?你的问题根本不清楚。请相应阅读[问]并[编辑]你的问题。 –