How to define custom sort function in javascript?

JavascriptFunctionSortingAutocomplete

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkiruganView Question on Stackoverflow
Solution 1 - JavascripterickbView Answer on Stackoverflow
Solution 2 - JavascriptLior ElromView Answer on Stackoverflow
Solution 3 - JavascriptKamyk.plView Answer on Stackoverflow
Solution 4 - Javascriptmonster_enzyView Answer on Stackoverflow