如何可以簡化陣列組織/組基於條件的陣列 - 的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'似乎是一個函數。情況並非如此嗎?你的問題根本不清楚。請相應閱讀[問]並[編輯]你的問題。 –