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-* 为第二组;
....
以此类推,求解
*/
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-* 为第二组;
....
以此类推,求解
*/
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' } ]
*/
8 回答5.8k 阅读✓ 已解决
9 回答9.2k 阅读
6 回答4.7k 阅读✓ 已解决
5 回答3.5k 阅读✓ 已解决
4 回答7.9k 阅读✓ 已解决
7 回答9.8k 阅读
5 回答7.1k 阅读✓ 已解决
题意里分组的共同点在于元素的第一个字符(应该说是连线符前的字符串)相同,所以可以用一个对象(其实就是类似字典的含义),把对应数据组合在一起放到同一个地方去。