Hello Readers! In this blog we are going to focus on the sorting method of an array in javascript. We use sort() method to sort the array in Javascript. The possible order in which an array can be sorted can be either in ascending or descending, alphabetic or numeric. But by default, it sorts the array in alphabetic and ascending order.
Basic Syntax : arryaName.sort([compareFunction]);
The parameter “compareFunction” is optional. This parameter specifies the sorting order.
For example :
var colors = ['Red','Blue','Black','Green','Orange','Yellow'];
alert(colors.sort()); // this will return Black,Blue,Green,Orange,Red,Yellow
we have an array of strings named colors and by default it is sorted in alphabetic order.
If the "compareFunction" is omitted, the values are first converted into strings and then compares strings in Unicode code point order.
For example: “black” comes before “red”. In a numeric sort, 12 comes before 30, but since numbers are converted to strings, “30” comes before “12” in Unicode order.
But in case if compareFunction is defined, values are sorted according to the return value of the compare function.
Suppose we have two elements being compared,i.e,x and y, then:
- in case if compareFunction(x,y) < 0, then
sort x to a lower index than b; x comes first.
- in case if compareFunction(x,y) = 0, then
leave the elements unchanged.
- in case if compareFunction(x,y) > 0, then
sort b to a lower index than y.
0 Comment(s)