I use atocomplete.jquery plugin to suggest input text, as the result I get this array:
['White 023','White','White flower', 'Teatr']
When I start to search something thats begin from te
substring it shows me array sorting like this:
'White','White 023','White flower', 'Teatr'
I need something like this:
'Teatr','White','White 023','White flower'
Any ideas?
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
JavaScript by default uses insertion sort for the sort() method.
sort() will sort on the string representation of the Array objects. For instance with two items "Name" and "Name 2" (where text and value are the same) the sort will put "Name" after "Name 2" (because it is actually comparing the strings "Name,Name" and "Name 2,Name 2").
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 question might help.
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:
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);
For Objects
try this:
function sortBy(field) { return function(a, b) { if (a[field] > b[field]) { return -1; } else if (a[field] < b[field]) { return 1; } return 0; }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With