Sorting is one important thing in programming, sorting will solve a lot of problems.
In this post, we are going to learn about sorting.
Sort Method:
The sort method is used to sort an array element by alphabetical order.
var _strArray = ["a","b","c","d","z","e"];
console.log(_strArray.sort())
output is ["a", "b", "c", "d", "e", "z"]If any element is an array is a capital letter, that will come first
var _strArray = ["a","b","c","d","z","e","Z"];
console.log(_strArray.sort())
output is ["Z","a", "b", "c", "d", "e", "z"]
Reverse Method:
The reverse method is used to reverse the array elements, we can use the reverse method for descending order.
var _strArray = ["a","b","c","d","z","e"];
console.log(_strArray.sort())
["z", "e", "d", "c", "b", "a"]
Compare method:
The sort method would not work for numeric values because "20" is bigger than "100".
In this case, we need to use compare function to sort the numeric values.
Without the compare method(Normal Sort)
var _numArr = [10,100,2,200,150,300];With the compare method
_numArr.sort();
[10, 100, 150, 2, 200, 300]
_numArr.sort(function(a, b){return a - b});
[2, 10, 100, 150, 200, 300]
The compare function will return the value as "Negative", "Zero", "Positive".
Thanks for posting such a Useful information .You have done a great job.
ReplyDeleteFull Stack Online Training
Full Stack Training
Full Stack Developer Online Training