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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS? #Jan 8 How to Install Xcode Command Line Tools on MacOS?
You might also like these
A Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscellaneousMake sure your links have descriptive textUI/UXWordPress: How to create a folder if it doesn’t already exist?WordPressA complete guide to add responsive YouTube videos using HTML and CSSCSSWordPress: How to change a blog address (URL)?WordPressQuick Introduction to 11 Array Iteration Methods in JavaScriptJavaScript