Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define custom sort function in javascript?

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?

like image 949
kirugan Avatar asked Feb 15 '11 11:02

kirugan


People also ask

Is there a sort function in JavaScript?

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.

What type of sort is sort () JavaScript?

JavaScript by default uses insertion sort for the sort() method.

How do you sort options in JavaScript?

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").


2 Answers

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);

More Info here on Array.sort.

like image 98
erickb Avatar answered Oct 06 '22 00:10

erickb


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;   }; } 
like image 31
Lior Elrom Avatar answered Oct 06 '22 01:10

Lior Elrom