对数组进行排序,以便空值始终位于最后 [英] Sort an array so that null values always come last
本文介绍了对数组进行排序,以便空值始终位于最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要对一个字符串数组进行排序,但我需要它以便null始终是最后一个。例如,数组:
I need to sort an array of strings, but I need it so that null is always last. For example, the array:
var arr = [a, b, null, d, null]
当按升序排序时,我需要将其排序为 [a,b,d,null,null]
,当按降序排序时,我需要将其排序为 [d,b,a,null,null]
。
When sorted ascending I need it to be sorted like [a, b, d, null, null]
and when sorted descending I need it to be sorted like [d, b, a, null, null]
.
这可能吗?我尝试了下面找到的解决方案,但这不是我需要的。
Is this possible? I tried the solution found below but it's not quite what I need.
推荐答案
查看 .sort()
并使用自定义排序执行此操作。
示例
Check out .sort()
and do it with custom sorting.
Example
var arr = [null, 'a', 'b', null, 'd'];
var alphabetically = function (ascending) {
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;
}
};
}
console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));
这篇关于对数组进行排序,以便空值始终位于最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文