YogeshChauhan.com
The Sort and Compare Functions in JavaScript
January 3, 2020

The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value, depending on the arguments:


function(a, b){return a - b}

When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

The “compare” function must take two arguments, often referred to as a and b. Then you make the compare function return 0, greater than 0, or less than 0, based on these values, a and b.

If the result is negative a is sorted before b. In other words, return less than 0 if a is less than b. So, if compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).

If the result is positive b is sorted before a. In other words, return greater than 0 if a is greater than b. So, if compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

If the result is 0 no changes are done with the sort order of the two values. In other words, return 0 if a equals b. So, if compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

So, the compare function has the following form:


function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

Now lets suppose this is our list of numbers to sort:


var numbers = [1,5,3.14];

When you call numbers.sort(compare), internally it will actually execute:


compare(1,5);     
// Returns -4, a is less than b

compare(1,3.14);  
// Return -2.14, a is less than b

compare(5,3.14);  
// returns 1.86, a is greater than b

The sort method can be conveniently used with function expressions:


var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]

ES2015 provides arrow function expressions with even shorter syntax.


let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]

Objects can be sorted, given the value of one of their properties.


var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort(function (a, b) {
  return a.value - b.value;
});

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

Sources

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

How to hide a DIV on clicks outside of it using jQuery?jQueryKeyValuePipe in Angular 9AngularAggregate Functions Examples in Postgres for BeginnersPostgresAlways add associated labels to your Form elementsUI/UXHow to remove border from :visited image, link or button?CSSSpecificity of attribute selectorsCSS