/**
* 数据排序 // 本次改动提交 是由老李确认并且认可的情况下修改的
* @param {* Array } arr 需要排序的数组
* @param {* String } field 排序字段
* @param {* String } order 排序方式 desc || asc
* @returns Array
*/
export const sortArray = (arr, field, order = 'asc') => {
// 汉字开头
const chineseReg = new RegExp('^[\u4e00-\u9fa5]')
let wordArr = []
let noWordArr = []
let isAsc = order === 'asc'
const collatorCN = new Intl.Collator('zh-CN');
const collatorUC = new Intl.Collator('en-US');
arr.forEach(item => {
if (chineseReg.test(item[field]) && field) wordArr.push(item)
else if (chineseReg.test(item)) wordArr.push(item)
else noWordArr.push(item)
})
if (field) {
wordArr = wordArr.sort((pre, next) => {
// if (isAsc) return pre[field].localeCompare(next[field])
// else return next[field].localeCompare(pre[field])
if (isAsc) return collatorCN.compare(pre[field] ?? '',next[field] ?? '')
else return collatorCN.compare(next[field] ?? '',pre[field] ?? '')
})
noWordArr = noWordArr.sort((pre, next) => {
if(field === 'ord') {
if (isAsc) return (pre[field] ?? '') - (next[field] ?? '')
else return (next[field] ?? '') - (pre[field] ?? '')
} else {
if (isAsc) return collatorUC.compare(pre[field] ?? '',next[field] ?? '')
else return collatorUC.compare(next[field] ?? '',pre[field] ?? '')
}
})
} else {
wordArr = wordArr.sort((pre, next) => {
if (isAsc) return collatorCN.compare(pre,next)
else return collatorCN.compare(next,pre)
})
noWordArr = noWordArr.sort((a,b) => {
if (isAsc) return collatorUC.compare(a,b)
else return collatorUC.compare(b,a)
})
}
let sortRelust = isAsc ? [...noWordArr, ...wordArr] : [...wordArr, ...noWordArr]
return sortRelust
}
复杂数组排序
于 2021-02-22 17:08:13 首次发布