根据条件组织/分组数组 - javascript

时间:2015-12-02 19:29:31

标签: javascript arrays

如何简化数组

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

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

1 个答案:

答案 0 :(得分:0)

遍历数组元素

  1. 分别提取国家和城市
  2. 更新国家/地区城市地图(跟踪映射到哪些城市的国家/地区的对象)
  3. 浏览此对象的键并使用您的国家/地区城市创建一个新阵列。如果该国家/地区有城市数组,请使用join(',')获取以逗号分隔的城市字符串。
  4. 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);