如何在javascript中定义自定义排序功能?

我使用atocomplete.jquery插件来建议输入文本,结果得到了这个数组:


['White 023','White','White flower', 'Teatr']

当我开始搜索从“ te”子字符串开始的内容时,它向我显示了这样的数组排序:


'White','White 023','White flower', 'Teatr'

我需要这样的东西:


 'Teatr','White','White 023','White flower'

有任何想法吗?


HUX布斯
浏览 704回答 3
3回答

慕姐4208626

该插件可能区分大小写。尝试输入Te而不是te。您可能将结果设置为不区分大小写。这个问题可能会有所帮助。对于上的自定义排序函数Array,您可以使用任何JavaScript函数并将其作为参数传递给Array的sort()方法,如下所示:var array = ['White 023', 'White', 'White flower', 'Teatr'];array.sort(function(x, y) {&nbsp; if (x < y) {&nbsp; &nbsp; return -1;&nbsp; }&nbsp; if (x > y) {&nbsp; &nbsp; return 1;&nbsp; }&nbsp; return 0;});// Teatr White White 023 White flowerdocument.write(array);

达令说

为了Objects试试这个:function sortBy(field) {&nbsp; &nbsp; return function(a, b) {&nbsp; &nbsp; &nbsp; &nbsp; if (a[field] > b[field]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; &nbsp; &nbsp; } else if (a[field] < b[field]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; };}

慕的地10843

function msort(arr){&nbsp; &nbsp; for(var i =0;i<arr.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; for(var j= i+1;j<arr.length;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(arr[i]>arr[j]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var swap = arr[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr[i] = arr[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr[j] = swap;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }return arr;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript