先根据顺序值排序,如果顺序值相同根据名称排序
const arr = [
{ id: 1, sort: 3, name: '张三' },
{ id: 2, sort: 1, name: '小明' },
{ id: 3, sort: 1, name: '王五' },
{ id: 4, sort: 1, name: '李四' },
{ id: 5, sort: 2, name: '周武' }
]
const da = arr.sort((a, b) => {
if (a.sort === b.sort) {
let targetA = a.name!= null && a.name.toString().toLowerCase()
let targetB = b.name!= null && b.name.toString().toLowerCase()
return targetA != null && targetA.localeCompare ? targetA.localeCompare(targetB) : targetA - targetB
}
return a.sort - b.sort
})
根据特定规则排序
var objs = [
{'name': 'A', 'type': '1'},
{'name': 'F', 'type': '6'},
{'name': 'E', 'type': '5'},
{'name': 'H', 'type': '8'},
{'name': 'D', 'type': '4'},
{'name': 'C', 'type': '3'}
]
objs.sort(function(a,b){
var order = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
return order.indexOf(a.type) - order.indexOf(b.type)
})
var result = objs.map(function(a){
return a['name']
})
console.log(result )
字符串与数字混合的字符串排序 – 先字符后数字
var list = ['a123', 'a11', 'a2']
var list1 = []
list1 = list.sort(function(a, b) {
return a.localeCompare(b, 'zh-CN', { numeric: true })
})
console.log(list1)
字符串与数字混合的字符串排序 – 先数字后字符
var list = ['abc123', 'abc11', 'abc2','c1','b1']
var list1 = []
list1 = list.sort(function(a, b) {
var an = a.match(/\d+(.\d+)?/g)[0];
var bn = b.match(/\d+(.\d+)?/g)[0];
if(parseFloat(an) > parseFloat(bn)) {
return 1
} else if(parseFloat(an) < parseFloat(bn)){
return -1
} else {
return a.localeCompare(b)
}
})
console.log(list1)