Computer >> Computer tutorials >  >> Programming >> Javascript

How to define custom sort function in JavaScript?


To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0.

The above process will sort the data in descending order. If you want the data in ascending order then reverse the above process.

Example

Following is the code −

var name = ['David', 'Adam', 'John', 'Bob'];
name.sort(function (first, second) {
   if (first > second) {
      return -1;
   }
   if (first < second) {
      return 1;
   }
   return 0;
});
console.log(name)

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo263.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo263.js
[ 'John', 'David', 'Bob', 'Adam' ]