Yogesh Chauhan's Blog

The Sort and Compare Functions in JavaScript

in JavaScript on 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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to include CSS and JavaScript files in your WordPress plugin?WordPressDynamically generate names in SCSS (animation example)SCSSWindow setTimeout() Method in JavaScriptJavaScriptA complete guide to add responsive YouTube videos using HTML and CSSCSSWhat’s Interpolation in SCSS (Sass)?SCSSDebugging in WordPress Part 3: SCRIPT_DEBUG and SAVEQUERIESWordPress