Array sorting methods in javascript

The JavaScript array sort() method is used to arrange the array elements in some order. By default, the sort() method follows the ascending order.

By default, the sort() method sorts the array elements in ascending order with the smallest value first and the largest value last.

Example: Let's see a simple example to sort the array of string elements.

        
var arr=["React Js","Node.js","Angular","Bootstrap"]
var result=arr.sort();

console.log(result); 

//Output :
[ 'Angular', 'Bootstrap', 'Node.js', 'React Js' ]
        
    

We can also use the reverse method to arrange strings in descending order.

Example: Let's see a simple example to sort the array of string elements.

        
var arr=["React Js","Node.js","Angular","Bootstrap"]
arr.sort();
var result=arr.reverse();

console.log(result); 

// Output : [ 'React Js', 'Node.js', 'Bootstrap', 'Angular' ]
        
    

Let’s sort the numbers using sort() method.

        
let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort();

console.log(numbers);

// Output : [ 0, 1, 10, 2, 20, 3, 30 ]
        
    

In this example, the sort() method places 10 before 2 because the string “10” comes before “2” when doing a string comparison.To fix this, you need to pass a compare function to the sort() method. The sort() method will use the compare function to determine the orders of elements.

The compare function of the sort() method accepts two arguments and returns a value that determines the sort order.

The compare() function accepts two arguments a and b. The sort() method will sort elements based on the return value of the compare() function with the following rules:

  1. If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, a will come first.
  2. If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, i.e., b will come first.
  3. If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions unchanged.
        
let numbers = [0, 10 , 22, 3, 100, 150, 222 ];
numbers.sort((a,b) => {
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(numbers);

// Output : [ 0, 3, 10, 22, 100, 150, 222 ]
        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top