Javascript 如何在javascript中定义自定义排序函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5002848/
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
How to define custom sort function in javascript?
提问by kirugan
I use atocomplete.jquery plugin to suggest input text, as the result I get this array:
我使用atocomplete.jquery插件来建议输入文本,结果我得到了这个数组:
['White 023','White','White flower', 'Teatr']
When I start to search something thats begin from te
substring it shows me array sorting like this:
当我开始搜索从te
子字符串开始的内容时,它会显示我这样的数组排序:
'White','White 023','White flower', 'Teatr'
I need something like this:
我需要这样的东西:
'Teatr','White','White 023','White flower'
Any ideas?
有任何想法吗?
回答by erickb
It could be that the plugin is case-sensitive. Try inputting Te
instead of te
. You can probably have your results setup to not be case-sensitive. This questionmight help.
可能是插件区分大小写。尝试输入Te
而不是te
. 您可能可以将结果设置为不区分大小写。这个问题可能会有所帮助。
For a custom sort function on an Array
, you can use any JavaScript function and pass it as parameter to an Array
's sort()
method like this:
对于 上的自定义排序函数Array
,您可以使用任何 JavaScript 函数并将其作为参数传递给 anArray
的sort()
方法,如下所示:
var array = ['White 023', 'White', 'White flower', 'Teatr'];
array.sort(function(x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
// Teatr White White 023 White flower
document.write(array);
回答by Lior Elrom
For Objects
try this:
为了Objects
试试这个:
function sortBy(field) {
return function(a, b) {
if (a[field] > b[field]) {
return -1;
} else if (a[field] < b[field]) {
return 1;
}
return 0;
};
}
回答by Kamyk.pl
or shorter
或更短
function sortBy(field) {
return function(a, b) {
return (a[field] > b[field]) - (a[field] < b[field])
};
}
let myArray = [
{tabid: 6237, url: 'https://reddit.com/r/znation'},
{tabid: 8430, url: 'https://reddit.com/r/soccer'},
{tabid: 1400, url: 'https://reddit.com/r/askreddit'},
{tabid: 3620, url: 'https://reddit.com/r/tacobell'},
{tabid: 5753, url: 'https://reddit.com/r/reddevils'},
]
myArray.sort(sortBy('url'));
console.log(myArray);
回答by monster_enzy
function msort(arr){
for(var i =0;i<arr.length;i++){
for(var j= i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
var swap = arr[i];
arr[i] = arr[j];
arr[j] = swap;
}
}
}
return arr;
}