今天遇到了个排序问题,当需要排序的字段缺少数据时,如下图
出现此问题的原因就是当数据 undefined 的时候,函数无法正确判断返回
下面贴出完整的代码, 亲测可用哦!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sort排序处理</title>
</head>
<body>
<div><button onclick="bigToSmall()">从大到小</button></div>
<div><button onclick="smallToBig()">从小到大</button></div>
<script>
var arr = [
{total_net_value: 123},
{total_net_value: 124},
{total_net_value: 12},
{total_net_value: 133},
{total_net_value: 33},
{},
{total_net_value: 143},
{total_net_value: 23},
{},
{total_net_value: 120},
{total_net_value: 213},
{total_net_value: 13},
]
function compare(property, type){
return function(a,b){
let value1 = a[property];
let value2 = b[property];
// console.log(value1, value2)
if (value1 == undefined) { // 当第一个值不存在时, 默认排序结果最大
return 1
}
if (value2 == undefined) { // 当第二个值不存在时, 默认排序结果最小
return -1
}
// 这样处理过后,只要数据不存在默认排在最后面
if (type == 'big') {
return value2 - value1
}else {
return value1 - value2
}
}
}
console.log('排序前', arr)
function bigToSmall () {
arr.sort(compare('total_net_value' ,'big'))
console.log('排序后', arr)
}
function smallToBig () {
arr.sort(compare('total_net_value', 'small'))
console.log('排序后', arr)
}
</script>
</body>
</html>