JavaScript Array Sort method

In the tutorial, JavaSampleApproach will introduce JavaScript Array Sort method.

To practice with JavaScript, we use Browser Console, by open a new browser tab then pressing F12.
Sort method

JavaScript Array provides a built-in sort() method with alphabetically sorting:

javascript array sort method - first look

JavaScript Array also supports a reverse() method, so we can combine it with sort() method to descend order:

javascript array sort method - reverse

Have any problems?

Yes, we will get a problem when sorting with other cases such as Numeric or Date arrays:

javascript array sort method - problems

-> 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});

javascript array sort method - compare method

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});

javascript array sort method - compare method descending array

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});

javascript array sort method - compare method object array

Example 2: sorting by (String type)

javascript array sort method - compare method object array - 2

By grokonez | November 17, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *