Javascript 对数组进行排序,以便空值始终排在最后
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29829205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort an array so that null values always come last
提问by Sirk
I need to sort an array of strings, but I need it so that null is always last. For example, the array:
我需要对一个字符串数组进行排序,但我需要它以便 null 总是最后。例如,数组:
var arr = [a, b, null, d, 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].
当升序排序[a, b, d, null, null]时,我需要像[d, b, a, null, null].
Is this possible? I tried the solution found below but it's not quite what I need.
这可能吗?我尝试了下面找到的解决方案,但这并不是我所需要的。
How can one compare string and numeric values (respecting negative values, with null always last)?
回答by AntouanK
Check out .sort()and do it with custom sorting.
Example
检查.sort()并使用自定义排序进行操作。例子
function alphabetically(ascending) {
return function (a, b) {
// equal items sort equally
if (a === b) {
return 0;
}
// nulls sort after anything else
else if (a === null) {
return 1;
}
else if (b === null) {
return -1;
}
// otherwise, if we're ascending, lowest sorts first
else if (ascending) {
return a < b ? -1 : 1;
}
// if descending, highest sorts first
else {
return a < b ? 1 : -1;
}
};
}
var arr = [null, 'a', 'b', null, 'd'];
console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));
回答by Bergi
Use a custom compare function that discriminates against nullvalues:
使用区null分值的自定义比较函数:
arr.sort(function(a, b) {
return (a===null)-(b===null) || +(a>b)||-(a<b);
});
For descending order, just swap aand bin the direct comparison:
对于降序,只需交换a和b直接比较:
arr.sort(function(a, b) {
return (a===null)-(b===null) || -(a>b)||+(a<b);
});
回答by Paul Roub
The simplest approach is to handle nullfirst, then deal with non-null cases based on the desired order:
最简单的方法是先处理null,然后根据所需顺序处理非空情况:
function sortnull(arr, ascending) {
// default to ascending
if (typeof(ascending) === "undefined")
ascending = true;
var multi = ascending ? 1 : -1;
var sorter = function(a, b) {
if (a === b) // identical? return 0
return 0;
else if (a === null) // a is null? last
return 1;
else if (b === null) // b is null? last
return -1;
else // compare, negate if descending
return a.localeCompare(b) * multi;
}
return arr.sort(sorter);
}
var arr = ["a", "b", null, "d", null]
console.log(sortnull(arr)); // ascending ["a", "b", "d", null, null]
console.log(sortnull(arr, true)); // ascending ["a", "b", "d", null, null]
console.log(sortnull(arr, false)); // descending ["d", "b", "a", null, null]
回答by cegprakash
Ascending
上升
arr.sort((a, b) => (a != null ? a : Infinity) - (b != null ? b : Infinity))
Descending
降序
arr.sort((a, b) => (b != null ? b : -Infinity) - (a != null ? a : -Infinity))
(For descending order if you don't have negative values in the array, I recommend to use 0 instead of -Infinity)
(对于降序,如果数组中没有负值,我建议使用 0 而不是 -Infinity)
回答by Steven Spungin
If you need natural sorting for numbers, or any of the options provided by Collator(including speed enhancements and respecting locale), try this approach, based off of Paul Roub's solution, cleaned up a bit. We almost always use numeric sorting, hence the defaults...
如果您需要对数字进行自然排序或由Collator(包括速度增强和尊重语言环境)提供的任何选项,请尝试这种方法,基于 Paul Roub 的解决方案,稍微清理一下。我们几乎总是使用数字排序,因此默认...
If you are not a Typescript fan, just strip off the :typespecs or copy from the snippet.
如果您不是 Typescript 粉丝,只需去掉:type规格或从代码片段中复制即可。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator
const naturalCollator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
const alphabeticCollator = new Intl.Collator(undefined, {});
function nullSort(descending: boolean = false, alphabetic: boolean = false) {
return function (a: any, b: any): number {
if (a === b) {
return 0;
}
if (a === null) {
return 1;
}
if (b === null) {
return -1;
}
let ret
if (alphabetic) {
ret = alphabeticCollator.compare(a, b)
} else {
ret = naturalCollator.compare(a, b)
}
if (descending) {
ret = -ret
}
return ret
};
}
Use it like this.
像这样使用它。
// numeric, ascending (default)
myList.sort(nullSort());
// alphabetic, descending
myList.sort(nullSort(true, true));
You can modify the factory method to take a collator instead, for greater flexibility.
您可以修改工厂方法以采用整理器,以获得更大的灵活性。
function nullSort(descending: boolean = false, collator: Collator = naturalCollator)
Working Snippet
工作片段
const naturalCollator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base'
});
const alphabeticCollator = new Intl.Collator(undefined, {});
function nullSort(descending = false, alphabetic = false) {
return function(a, b) {
if (a === b) {
return 0;
}
if (a === null) {
return 1;
}
if (b === null) {
return -1;
}
let ret
if (alphabetic) {
ret = alphabeticCollator.compare(a, b)
} else {
ret = naturalCollator.compare(a, b)
}
if (descending) {
ret = -ret
}
return ret
};
}
const items = [null, 10, 1, 100, null, 'hello', .1, null]
console.log(items.sort(nullSort()));
回答by Vitaliy Terziev
like this, note: this will only push the null's to the back
像这样,注意:这只会将空值推到后面
var arr = ["a", null, "b"];
var arrSor = [];
arr.forEach(function (el) {
if (el === null) {
arrSor.push(el);
} else {
arrSor.unshift(el);
}
});
回答by Shubham
Do it like:
这样做:
var arr = [a, b, null, d, null]
foreach ($arr as $key => $value) {
if($value == null)
unset($arr[$key]);
$arr[] = $value;
}
// rebuild array index
$arr = array_values($arr);
echo '<pre>';print_r($arr);die;

