js 数组分组?

var list = ['1-10','1-20','1-22','2-2','2-3','2-4','3-1','3-5','4-6','5-10'];
/*
如何将上面数组分成5组?
如:1-* 为第一组;
   2-* 为第二组;
   ....
以此类推,求解
*/
阅读 7.9k
4 个回答

题意里分组的共同点在于元素的第一个字符(应该说是连线符前的字符串)相同,所以可以用一个对象(其实就是类似字典的含义),把对应数据组合在一起放到同一个地方去。

var obj = {};
var list = ['1-10','1-20','1-22','2-2','2-3','2-4','3-1','3-5','4-6','5-10'];
list.forEach(function(e){
  var index = e.split('-')[0];
  if(!obj[index]){
    obj[index] = [];
  }
  obj[index].push(e);

})
  var arr1=[],arr2=[],arr3=[],arr4=[],arr5=[];
 for(var I = 0;I< list.length;I++){
    var a = list[I].str.substr(0, 2)
    if(a == 1){
      arr1.push(list[I])
    }
    if(a == 2){
      arr2.push(list[I])
    }
    if(a == 3){
      arr3.push(list[I])
    }
    if(a == 4){
      arr4.push(list[I])
    }
    if(a == 5){
      arr5.push(list[I])
    } 
  }

类似这样的也可以:

输入:

let arr = [
    "四川省",
    "四川省/绵阳市",
    "四川省/广元市",
    "贵州省/贵阳市",
    "贵州省/安顺市",
    "湖北省",
    "湖北省/武汉市"
]

输出:

[{
    "loc_province": "四川省",
    "loc_city": ["绵阳市", "广元市"]
}, {
    "loc_province": "贵州省",
    "loc_city": ["贵阳市", "安顺市"]
}]

根据省份进行分组。

函数:

let group = (array, spliter) => {
    let location = {}
    location['loc_city'] = []
    let currentProvince = ''
    let locations = []
    let size=array.length
    for (let index = 0; index <size; index++) {
        const element = array[index];
        if (element.includes(spliter)) {
            let province = element.split(spliter)[0]
            let city = element.split(spliter)[1]
            if (currentProvince !== province) {
                currentProvince = province
                locations.push(location)
                location = {};
                location['loc_city'] = []
                location['loc_province'] = province
                location['loc_city'].push(city)
            } else {
                location['loc_city'].push(city)
            }
            index === size - 1 && locations.push(location)
        }
    }
    locations.shift();
    return locations;
}

测试:

let arr = [
    "四川省",
    "四川省/绵阳市",
    "四川省/广元市",
    "贵州省/贵阳市",
    "贵州省/安顺市",
]
console.log(group(arr,'/'));
/*[{
    "loc_province": "四川省",
    "loc_city": ["绵阳市", "广元市"]
}, {
    "loc_province": "贵州省",
    "loc_city": ["贵阳市", "安顺市"]
}]
*/
var list = ['1-10', '1-20', '1-22', '2-2', '2-3', '2-4', '3-1', '3-5', '4-6', '5-10'];
console.log(group(list,'-'));
/*
[ { loc_city: [ '10', '20', '22' ], loc_province: '1' },
  { loc_city: [ '2', '3', '4' ], loc_province: '2' },
  { loc_city: [ '1', '5' ], loc_province: '3' },
  { loc_city: [ '6' ], loc_province: '4' },
  { loc_city: [ '10' ], loc_province: '5' } ]
*/
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏