[导读]:需求:数字和英文按 123,abc顺序,中文按拼音首字母排序constobj=["A楼栋","商铺",45,"车位",2,"库房",6,1,"公寓",8,"办公","cccc","ppp","EEEE"]或者数组别的格式[{...
需求:数字和英文按 123,abc顺序,中文按拼音首字母排序
const obj=[ "A楼栋","商铺",45,"车位",2,"库房",6,1,"公寓",8, "办公","cccc","ppp","EEEE"] 或者数组别的格式 [ { "occupancyRateSum": 20.00511067089993, "rentableAreaSum": 44221.2, "rentedAreaSum": 8846.5, "vacantAreaSum": 35374.7, "item": "A楼栋" }, ..... ] 下面有源码处理方式
Array 的默认排序方法 sort
sort默认按字符的Unicode编码进行排序
// 获取排序前的Unicode编码
obj.forEach(i => console.log(i.toString().charCodeAt(0))) const sort1 = [...obj] sort1.sort() // 数字>英文>字母> 文字[1,...,"A楼栋"...,"cccc",...,"办公",...]
// 查看排序后的Unicode编码
sort1.forEach(i => console.log(i.toString().charCodeAt(0)))
可以看到默认的排序方式,无法完成对中文字符按拼音首字母排序,因此需要借助 localeCompare 方法进行辅助排序
完整的排序方案#
export function mixSort(_a, _b) { const reg = /[a-zA-Z0-9]/ // 比对仅针对字符串,数字参与对比会导致对比的字符串转为number类型,变成NaN const a = _a.toString() const b = _b.toString() // 比对0号位的原因是字符串中有可能出现中英文混合的情况,这种仅按首位排序即可 if (reg.test(a[0]) || reg.test(b[0])) { if (a > b) { return 1 } else if (a < b) { return -1 } else { return 0 } } else { return a.localeCompare(b) } }
const sort2 = [...obj] sort2.sort((a, b) => mixSort(a, b))
// 数字>英文>字母> 文字[1,...,"A楼栋"...,"cccc",...,"办公",...]
该方法已基本符合预期,如果需要针对首位英文或数字字符相同,后面中文二次排序的情况,就需要额外处理,此处不再展开
[ { "occupancyRateSum": 20.00511067089993, "rentableAreaSum": 44221.2, "rentedAreaSum": 8846.5, "vacantAreaSum": 35374.7, "item": "A楼栋" }, { "occupancyRateSum": 11.748244777054644, "rentableAreaSum": 70219, "rentedAreaSum": 8249.5, "vacantAreaSum": 61969.5, "item": "办公" }, { "occupancyRateSum": 12.152269399707174, "rentableAreaSum": 683, "rentedAreaSum": 83, "vacantAreaSum": 600, "item": "车位" }, { "occupancyRateSum": null, "rentableAreaSum": 0, "rentedAreaSum": 0, "vacantAreaSum": 0, "item": "公寓" }, { "occupancyRateSum": 15.436116793751161, "rentableAreaSum": 537.7, "rentedAreaSum": 83, "vacantAreaSum": 454.7, "item": "库房" }, { "occupancyRateSum": 26.073805202661827, "rentableAreaSum": 1653, "rentedAreaSum": 431, "vacantAreaSum": 1222, "item": "商铺" } ]
sort2.sort((a, b) => mixSort(a.item, b.item))
对什么值排序写什么值便可!!!
本文来自E先生的博客,如若转载,请注明出处:https://javajz.cn
留言区