根据条件分组或重新排列数组元素 - javascript

时间:2015-12-02 15:35:48

标签: javascript arrays

我有一个名为' country'看起来像:

country=[
            {
                "name": "china",
                "id": "country:china"
            }, {
                "name": "city1",
                "id": "country:country1>city1"
            }, {
                "name": "city2",
                "id": "country:country1>city2"
            }, {
                "name": "city3",
                "id": "country:country1>city3"
            }, {
                "name": "korea",
                "id": "country:korea"
            }, {
                "name": "australia",
                "id": "country:australia"
            }
        ]

我正在考虑将上面的数组重新排列/分组为:

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

我写了以下代码,但这并没有给我想要的结果:

$scope.countryInfo = function(itemData){
        var countryResult = [];
        for(var i=0; i<itemData.length; i++){
            var countryItem = itemData[i];
            if(countryItem.id.indexOf('>') > -1){ //Found city
                var itemId = countryItem.id.substr(0, countryItem.id.indexOf('>'));
                for(var j=0; j<$scope.countryData.length; j++){
                    if($scope.countryData[j].id == itemId){
                        var _parentChild = $scope.countryData[j].name + "( " + countryItem.name + " ) ";
                        countryResult.push(_parentChild);
                    }
                }
            }
            else{
                countryResult.push(countryItem.name);
            }
        }
        return countryResult;
    }

结果就是这样 - [ china, country1(city1), country1(city2), country1(city3)), korea, australia]

请告诉我如何实现预期的数组结果。

编辑:我只是想将数组[ china, country1(city1), country1(city2), country1(city3)), korea, australia]简化为[ china, country1(city1, city2, city3), korea, australia]

3 个答案:

答案 0 :(得分:0)

您可以使用临时对象,然后将对象的属性映射到所需的数组。

&#13;
&#13;
var country = [{ "name": "china", "id": "country:china" }, { "name": "city1", "id": "country:country1>city1" }, { "name": "city2", "id": "country:country1>city2" }, { "name": "city3", "id": "country:country1>city3" }, { "name": "korea", "id": "country:korea" }, { "name": "australia", "id": "country:australia" }],
    temp = {},
    result;

country.forEach(function (a) {
    var b = a.id.split(/\:|\>/g);
    temp[b[1]] = temp[b[1]] || [];
    if (b[2]) {
        temp[b[1]].push(b[2]);
    }
});
result = Object.keys(temp).map(function (k) {
    if (temp[k].length) {
        return k + '(' + temp[k].join(', ') + ')';
    }
    return k;
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我已将reduce与具有keys属性的初始对象一起使用以捕获元素的位置:

function sorter(countty) {
  var obj = country.reduce(function (p, c, i) {
    var key, id = c.id.split(/[:>]/);
    if (id.length === 3) {
      key = id[1];
      if (!p[key]) {
        p[key] = [];
        p.keys.push(key);
      }
      p[key].push(id[2]);
    } else {
      p.keys.push(c.name);
    }
    return p;
  }, { keys: [] });

  return obj.keys.map(function (el) {
    return obj[el] ? el + '(' + obj[el].join(', ') + ')' : el;
  });
}

sorter(country);

DEMO

答案 2 :(得分:0)

我写了这段代码,将你的第一个阵列(在你的#34; EDIT&#34;中)改成你的第二个阵列,我不是说它很干净,但它有效:< / p>

对数组进行排序,然后尝试确定这些国家是否匹配,以及是否有需要合并的城市......

&#13;
&#13;
//an array of countries, some of which include comma delimited cities wrappedin parentheses
var arrayPlaces = ["china", "country1(city1)", "korea", "country1", "country1(city2)", "country1(city3)", "australia", "korea", "home(delicious)", "home(nacho)", "home(plate)"];

//creates an alphabatized version of the array, to simplify finding matching countries
var arrayPlacesSorted = arrayPlaces.sort();

//defines a regular expression (to search for matches countries)


var hasCity = function (sTemp) {
  var re = /\(/;
  if (re.test(sTemp)) {
    return true;

  } else {
    return false;
  }

};

var countryRe = /(.*?)\(.*?\)/;
var cityRe = /.*?\((.*?)\)/;

//function that loops through array, checks for matching countries, combines/adds cities
var groupCities = function (aTemp) {
  var currentCountry,
    currentCity,
    nextCountry,
    nextCity;

  for (var i = 0; i < (aTemp.length); i++) {
    if (hasCity(aTemp[i])) {
      currentCountry = countryRe.exec(aTemp[i])[1];
      currentCity = cityRe.exec(aTemp[i])[1];
    } else {
      currentCountry = aTemp[i];
      currentCity = false;
    }
    if (hasCity(aTemp[i + 1])) {
      nextCountry = countryRe.exec(aTemp[i + 1])[1];
      nextCity = cityRe.exec(aTemp[i + 1])[1];
    } else {
      nextCountry = aTemp[i + 1];
      nextCity = false;
    }
    if (currentCountry === nextCountry && nextCity && currentCity) {
      aTemp[i] = currentCountry + "(" + currentCity + "," + nextCity + ")";
      aTemp.splice(i + 1, 1);
      i = 0;
    } else if (currentCountry === nextCountry && nextCity) {
      aTemp[i] = currentCountry + "(" + nextCity + ")";
      aTemp.splice(i + 1, 1);
      i = 0;
    } else if (currentCountry === nextCountry && currentCity) {
      aTemp[i] = currentCountry + "(" + currentCity + ")";
      aTemp.splice(i + 1, 1);
      i = 0;
    } else if (currentCountry === nextCountry) {
      aTemp[i] = currentCountry;
      aTemp.splice(i + 1, 1);
      i = 0;
    }
  }
  return aTemp;
};

var result = groupCities(arrayPlacesSorted);
console.log(result);
&#13;
&#13;
&#13;