Sorting of array in JavaScriptWe can sort elements of an array by using sort() function in JavaScript. This sort() function once applied changes the positions of the elements and arrange them in alphabetical or increasing order. Here is the basic syntax of the sort function.
By default this sort is in lexicographical order or dictionary order. Check this example and its output.
Output is here
The sorting is done according to string Unicode code points.
Optional Campare functionWe can define our sorting algorithm in a function and JavaScript will use the function to sort the array. Function conditions are hereThe function will accept two arguments and these arguments are to be compared for the algorithm. The function will return numbers based on the comparison of the two arguments. returned number is < 0 : The first argument should appear before the second argument. returned number is > 0 : The first argument should appear after the second argument. returned number is equal to 0 then both the arguments should be equal. Let us try to sort the array elements now by using optional compare function.
Output is here
To change the order to descending, we must change the comparison inside the function or change this line ( swap a1,a2 ).
Now let us try to create an array and then display them to see the elements and their order. After this we will apply sort() function and then again we will display the elements of the array to check the order.
Here is the code.
In the order of length of the elementHere is the code.
Output is here
This article is written by plus2net.com team.
![]() |
![]() |