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);
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);
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);
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);
Output:- [15,12,10,7,5,3];
Javascript Array Sorting – Interview Questions
Q 1: Which method sorts arrays?
Ans: sort().
Q 2: Default sort order?
Ans: Alphabetical.
Q 3: How to sort numbers correctly?
Ans: Use the compare function.
Q 4: Does sort modify the original array?
Ans: Yes.
Q 5: Can sort be descending?
Ans: Yes.
Javascript Array Sorting – Objective Questions (MCQs)
Q1. Which method is used to sort an array in JavaScript?
Q2. By default, sort() sorts elements as ______.
Q3. Which function is used to sort numbers correctly?
Q4. What does arr.sort((a, b) => a - b) do?
Q5. Does sort() modify the original array?