How do I sort the list of items(alphabetic/numeric) in an array either in ascending/descending order
This example demonstrates sorting the list of alphabetic/numeric items in an array in ascending/descending order.
In the solutions shown below, the elements in an array are sorted in ascending/descending order using a "storeEval" command and stored into a variable.
Solution:
# | Command | Target | Value |
---|---|---|---|
Sorting the alphabetic items in an array in ascending order using "sort()" JavaScript method | |||
1 | storeEval |
function f(){ var colors_list = ["Green","Yellow","Blue"]; var colors=colors_list.sort(); return colors[0]+","+colors[1]+","+colors[2]; }f(); |
sorted_list |
Sorting the alphabetic items in an array in descending order using "sort()" and "reverse()" JavaScript method | |||
2 | storeEval | function f(){ var colors_list = ["Green","Yellow","Blue"]; var colors=colors_list.sort().reverse(); return colors[0]+","+colors[1]+","+colors[2]; }f(); | sorted_list |
Sorting the numeric items in an array in ascending order using "sort()" JavaScript method with a compare function |
|||
3 | storeEval | function f(){ var numbers_list = [19,3,45]; var numbers=numbers_list.sort(function(a,b){return a-b;}); return number[0]+","+number[1]+","+number[2]; }f(); |
sorted_list |
Sorting the numeric items in an array in descending order using "sort()" JavaScript method with a compare function |
|||
4 | storeEval | function f(){ var numbers_list = [19,3,45]; var numbers=numbers_list.sort(function(a,b){return b-a;}); return number[0]+","+number[1]+","+number[2]; }f(); |
sorted_list |
Tips, Tricks, Gotchas & Best Practices:
- As a best practice, it is always advisable to define the variable names without any spaces and if you want to differentiate the words, use underscores.