How to define custom sort function in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Published on 09-Nov-2020 07:37:41
Advertisements