本文介绍了如何对具有空值的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与该主题相关的问题很多,但我找不到适合我的情况的正确解决方案.
There are quite a few question related to the topic, but I couldn't find the right solution for my case.
var arr = [a, b, null, d, null]
并使用以下逻辑对该数组进行排序
and am sorting this Array with below logic
return function(a,b){
if(a === null){
return 1;
}
else if(b === null){
return -1;
}
else if(a === b){
return 0;
}
else if(ascending) {
return a < b ? -1 : 1;
}
else if(!ascending) {
return a < b ? 1 : -1;
}
};
我得到
Ascending : [a, b, d, null,null]
Descending : [d, b, a, null,null]
Expected : [null, null,d, b, a]
我在做什么错了?
推荐答案
function getSort (ascending) {
// if ascending, `null` will be pushed towards the end of the array by returning 1
var nullPosition = ascending ? 1 : -1
return function (a, b) {
// if a is null, push it towards whichever end null elements should end up
if (a == null) return nullPosition
// Note: at this point, a is non-null (previous if statement handled that case).
//
// If b is null, it must therefore be placed closer to whichever end the null
// elements should end up on. If ascending, null elements are pulled towards
// the right end of the array. If descending, null elements are pulled towards
// the left.
//
// Therefore, we return -nullPosition. If ascending, this is -1, meaning a comes
// before b; if descending, this is 1, meaning a comes after b. This is
// clearly the correct behavior, since ascending will push b, which is null,
// towards the end of the array (with -1) and descending will push b towards
// the beginning of the array.
if (b == null) return -nullPosition
// OTHERWISE, both elements are non-null, so sort normally.
// if a < b AND
// if ascending, a comes first, so return -1 == -nullPosition
// if descending, a comes after, so return -nullPosition == -(-1) == 1
if (a < b) return -nullPosition
// return the opposite of the previous condition
if (a > b) return nullPosition
// return 0 if both elements are equal
return 0
}
}
function write (arr) { arr.forEach(function (d) { document.write(d + "<br>")})}
var toSort = ['a', 'b', null, 'd', null]
var sortA = getSort(true)
var sortD = getSort(false)
document.write("<br>ASCENDING<br>")
write(toSort.sort(sortA))
document.write("<br>DESCENDING<br>")
write(toSort.sort(sortD))
这篇关于如何对具有空值的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!