Hello Readers,
sorting string array :
sort method in jquery is used to sort array elements in alphabetically order this type of sorting is called as sorting through string array.
For Example :
$(document).ready(function(){
var list = [ Apple,Orange,Banana];
$(#mydiv).html(list.join());
list = list.sort();
$(#sorted).html(list.join());
});
Output before sorting :
Apple
Orange
Banana
Output after sorting :
Apple
Banana
Orange
sorting numerical array :
numerical array sorting in jquery is used to sort the numeric elements.
For Example :
$(document).ready(function(){
var list = [ 20,3100,50];
$(#mydiv).html(list.join());
list = list.sort();
$(#sorted).html(list.join());
});
Output before sorting :
100
20
3
50
In the above code, sort method not sort the numerical array in proper order because sort method sorts on the basis of ASCII values.
So, to sort the numerical value in proper order we use the comparison function with sort().
For Example :
Output after sorting in numerical array :
$(document).ready(function(){
var list = [ 20,3100,50];
$(#mydiv).html(list.join());
list = list.sort(function(a,b){
return a-b;
});
$(#sorted).html(list.join());
});
Output before sorting :
3
20
50
100
0 Comment(s)