Javascript Array Sorting

You can sort the Array element (which is numeric) in Ascending or Descending order through below code.

Ascending Order:- There are two ways to Sorting in Ascending Order.

1) Array Sorting without function


var arr=[10,5,7,3,12,15];
var temp;
let i;
let j;
for( i=0; i<arr.length; i++)
{
for(j=i; j>0; j--){

  if(arr[j-1] > arr[j]){
        
        temp=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=temp;

		}
	}
}
console.log(arr);

Try it Yourself

Output:-[3,5,7,10,12,15];

2) Array Sorting with sort() function


  var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return a-b;
});

console.log(sort_arr);  

Try it Yourself

Output:- [3,5,7,10,12,15];

Descending Order:- There are two way in descending Order.

1) Array Sorting without function


var arr=[10,5,7,3,12,15];
var temp;
let i;
let j;
for( i=0; i<arr.length; i++)
{
for(j=i; j>0; j--){

  if(arr[j] > arr[j-1]){
        
        temp=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=temp;

		}
	}
}
console.log(arr);

Try it Yourself

Output:- [15,12,10,7,5,3];

2) Array Sorting with sort() function


 var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return b-a;
});

console.log(sort_arr);  

Try it Yourself

Output:- [15,12,10,7,5,3];