原数据格式:
let arr = [
{ _index: 'aa', module_id: '7310', data: [] },
{ _index: 'aa', module_id: '7311', data: [] },
{ _index: 'aa', module_id: '7312', data: [] },
{ _index: 'aa', module_id: '7312', data: [] },
{ _index: 'bb', module_id: '7410', data: [] },
{ _index: 'bb', module_id: '7410', data: [] },
{ _index: 'bb', module_id: '7411', data: [] },
]
1.只根据_index条件分组,分为2组 aa一组,bb一组
(1)groupBy分组
sortClass(sortData) {
const groupBy = (array, f) => {
let groups = {}
array.forEach((o) => {
let group = JSON.stringify(f(o))
groups[group] = groups[group] || []
groups[group].push(o)
})
return Object.keys(groups).map((group) => {
return groups[group]
})
}
const sorted = groupBy(sortData, (item) => {
return item._index
})
return sorted
},
调用 this.arr= this.sortClass(that.arr)
分组后格式:
图1:
(2)js分组
function sortClass(array, key, resKey = "list") {
if (!key) return array;
var aMap = [];
var aResult = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (aMap.indexOf(item[key]) === -1) {
var oItem = {};
oItem[resKey] = [item];
oItem[key] = item[key];
aResult.push(oItem);
aMap.push(item[key]);
} else {
var index = aMap.indexOf(item[key]);
aResult[index][resKey].push(item);
}
}
return aResult;
}
//调用
this.arr = this.sortClass(this.arr,'_index')
分组后格式:
图2:
2.根据_index和moduleId条件分组,分为5组, (aa,7310)一组,(aa,7311)一组,(aa,7312)一组,(bb,7410)一组,(bb,7411一组)
sortClass(array, keyArry, resKey = 'list') {
if (keyArry.length <= 0) return array
var aMap = []
var aResult = []
for (var i = 0; i < array.length; i++) {
var item = array[i]
var repetitionValue = ''
var repetitionKey = ''
keyArry.forEach((keyValue) => {
repetitionKey = repetitionKey + keyValue
repetitionValue += '' + item[keyValue]
})
if (aMap.indexOf(repetitionValue) === -1) {
//没有重复
var oItem = {}
oItem[resKey] = [item]
oItem[repetitionKey] = repetitionValue //item[key] //分组的字段
aResult.push(oItem)
aMap.push(repetitionValue)
} else {
//重复了
var index = aMap.indexOf(repetitionValue)
aResult[index][resKey].push(item)
}
}
return aResult
},
//调用
this.arr = this.sortClass(this.arr, ['_index', '_moduleId'])
分组后格式:
图3:
改成[[],[]]数据格式,代码如下:
sortClass(array, keyArry, resKey) {
if (keyArry.length <= 0) return array
var aMap = []
var aResult = []
for (var i = 0; i < array.length; i++) {
var item = array[i]
var repetitionValue = ''
var repetitionKey = ''
keyArry.forEach((keyValue) => {
repetitionKey = repetitionKey + keyValue
repetitionValue += '' + item[keyValue]
})
if (aMap.indexOf(repetitionValue) === -1) {
// //没有重复
// var oItem = {}
// oItem[resKey] = [item]
// oItem[repetitionKey] = repetitionValue //item[key] //分组的字段
// aResult.push(oItem)
aMap.push(repetitionValue)
aResult.push([item])
} else {
// //重复了
var index = aMap.indexOf(repetitionValue)
// aResult[index][resKey].push(item)
aResult[index].push(item)
}
}
return aResult
}
调用
that.arr= that.sortClass(that.arr, [
'_index',
'module_id',
])
分组后格式:
图4: