In the tutorial, JavaSampleApproach will introduce JavaScript Array Sort method.
Sort method
JavaScript Array provides a built-in sort()
method with alphabetically sorting:
JavaScript Array also supports a reverse()
method, so we can combine it with sort()
method to descend order:
Have any problems?
Yes, we will get a problem when sorting with other cases such as Numeric or Date arrays:
Why?
-> Because by default, JavaScript Array sort()
supports for String values. To resolve it, We can use Compare function.
Compare function
The compare function is defined to customize the sorting with other types such as Numberic, Date, Object beside the default setting with String values: numbers.sort(function(a, b) {return a-b});
Note: the compare function should return a negative, zero, or positive value.
How it works?
-> sort()
uses the compare function with each pair of 2 values. Then uses the returned value (negative, positive or zero) from compare function to decide a right order of each element.
We can also define a compare function for descending-order array: numbers.sort(function(a, b) {return b-a});
Array Sort with Object
With the support of compare function, we can use sort()
with Object Array:
– Example 1: sorting by customer.age
(Numberic type)
customers.sort(function(cust1, cust2){return cust1.age - cust2.age});
– Example 2: sorting by customer.name
(String type)
customers.sort(function(cust1, cust2){ var name1 = cust1.name.toLowerCase(); var name2 = cust2.name.toLowerCase(); if(name1 < name2){ return -1;} if(name1 > name2){ return 1;} return 0; });