js对象数组进⾏分组排序 使⽤:
let dataSource = [
{
groupxxx: 2,
sortxxx: 1,
},
{
groupxxx: 1,
sortxxx: 2,
},
{
groupxxx: 1,
sortxxx: 1,
},
{
groupxxx: 2,
sortxxx: 2,
}
]
dataSource = upAndSort("groupxxx", "sortxxx", dataSource)
结果:
[
{
groupxxx: 1,
sortxxx: 1,
},
{
groupxxx: 1,
sortxxx: 2,
},
{
groupxxx: 2,
sortxxx: 1,
},
{
groupxxx: 2,
sortxxx: 2,
}
]
代码:
/**
* 分组排序算法
*/
groupAndSort(groupFields, sortFields, list){
if(Array.isArray(list) && list.length <= 0) {
return []
}
let tempList = []
list = this.sortByFields(groupFields, list)
let tempGroupValue = list[0][groupFields]
for (let i = 0; i < list.length; i++) {
if(!list[i]) {
continue
}
if (list[i][groupFields] != tempGroupValue) {
tempGroupValue = list[i][groupFields]
}
this.addObjToList(groupFields, sortFields,tempGroupValue, list[i], tempList)
list.splice(i, 1);
i--;
}
return tempList
},
addObjToList(groupFields, sortFields, tempGroupValue, obj, list){
let tempLength = list.length
for (let i = 0; i < list.length; i++) {
if(list[i][groupFields] == tempGroupValue && obj[sortFields] <= list[i][sortFields]) { list.splice(i, 0, obj);
return
}
}
if(tempLength == list.length) {
list.push(obj)
}
},
sortByFields(sortFields, list){
return list.sort((a, b) => {
if(a[sortFields] < b[sortFields]) {
sort函数 jsreturn -1
}
if(a[sortFields] > b[sortFields]) {
return 1
}
return 0
})
},
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论