In JavaScript, we have a couple of more methods to sort the array, find min/max in the array, reverse the array, etc. These are very much useful while solving complex programming questions. Let us see them one by one:
sort():
Example:
var stud = ["Adarsh", "Utkarsh", "Harsh", "Shivam"];
stud.sort();
Now stud will become: ["Adarsh", "Harsh", "Shivam", "Utkarsh"]
reverse():
Example:
var stud = ["Adarsh", "Utkarsh", "Harsh", "Shivam"];
stud.reverse();
Now stud will become: ["Shivam", "Harsh", "Utkarsh", "Adarsh"]
In JavaScript, if we use the sort() function, it will sort values as strings. That means 68 will be kept after 1222 as it is lexicographically greater than 1222 but mathematically it should present before 1222. So we can’t use the sort() function directly for sorting numbers. We may solve this issue using compare function.
Compare Function
Using compare function we may define our own sorting order over the elements. The compare function should return a negative, zero, or positive value, depending on the arguments.
Let us take an example to understand it. If we sort the array of numbers then it will not be sorted mathematically but lexicographically. Suppose we want to make a compare function to sort them in increasing order mathematically.
The required function will be: function(a, b){return a - b} and to sort using it we will write array.sort(function(a, b){return a - b}).
The compare function compares all the values in the array, two values at a time (a, b) and
Example:
var A = [4, 20, 10, 50];
A.sort(function(a, b){return a-b});
Now A will be sorted and will become: [4, 10, 20, 50]
Finding max of an array:
We may use Math.max.apply to find the highest number in an array.
Example:
var A = [4, 50, 1, 20];
var z = Math.max.apply(null,A);
Here 50 will be stored in z.
Finding min of an array:
We may use Math.min.apply to find the lowest number in an array.
Example:
var A = [4, 20, 1, 50];
var z = Math.min.apply(null,A);
Here 1 will be stored in z.
Try the following example in the editor below.
You are given an array of integers with its size. Sort them and print them. Please note that you have to print one element in one line.
Sample Input:
4(Size)
10
2
30
14
Sample Output:
2
10
14
30