In this post, we will be learning about some common JavaScript array sorting functions.
Sort()
Sort()
arranges your elements in ascending alphabetical or numeric order.
JavaScript Code
var fruits = ["orange", "apple", "banana", "pears", "plum"];
fruits.sort();
Results
Reverse()
Reverse()
arranges your elements in descending order, either alphabetically or numerically.
JavaScript Code
var fruits = ["apple", "banana", "pears", "plum"];
fruits.reverse();
Results
How To Sort Numbers
You cannot simply add an array of numbers and expect sort()
to take care of it. For example, it will see 10 as smaller than 9.
If you wish to sort an array of numbers, you need to create a function such as seen below.
JavaScript Code
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});