How to Sort an Array in JavaScript
Today, we will explain to you how to sort an array in javascript using sort method of the array. Sorting is nothing but lets you arrange data in a required form.
Array sorting in Javascript, Sorting Arrays of Strings in JavaScript, JavaScript Array Sort, Array sort() Method, Sorting an array of objects by property values, How to sort an array in JavaScript,javascript sort an array of numbers.
Checkout more articles on JavaScript
The sort() method is used to rearranges the elements of an array in order and returns that array. The sort order can be alphabetic, numeric, ascending or descending. By default, sort() method is alphabetic order for the words and ascending order for the numbers.
Different ways to Sort an Array in JavaScript
- Sort method
- Sorting array in ascending order
- Sorting array in descending order
- Reversing the sorted array
1. Sort method
The Sort() method sorts the elements into an alphabetical order and returns the sorted array. This method works well for strings not for number.
1 2 3 4 | var colours = ["Blue", "Orange", "White", "Pink"]; colours.sort(); // Output: ["Blue", "Orange", "Pink", "White"] |
If we use sort() method for numerical array, the results aren’t what we might expect. Because the numeric array gets converted to a string by the sort() method. see below example.
1 2 3 4 | var numbers = [84,45,7,0,17,34,28] numbers.sort(); // Output: [0, 17, 28, 34, 45, 7, 84] |
So, we have to customize the array sort. To customize the sort order, we pass function to compare two items in the array and sends the values to the compare function. The compare function follows the below test cases:
- If the compare function returns a value less than 0, a is sorted before b.
- If the compare function returns a value greater than 0, b is sorted before a.
- If the compare function returns 0, then no change appears in the sort order of the values a & b.
2. Sorting array in ascending order
The below example describes how to sort the array in ascending order.
1 2 3 4 | var numbers = [84,45,7,0,17,34,28] numbers.sort((a, b) => a - b); // Output: [0, 7, 17, 28, 34, 45, 84] |
3. Sorting array in descending order
Check below example that describes how to sort the array in descending order.
1 2 3 4 | var numbers = [84,45,7,0,17,34,28] numbers.sort((a, b) => b - a); // Output: [84, 45, 34, 28, 17, 7, 0] |
4. Reversing the sorted array
To reverse the sorted array, first we have to sort an array using sort method that after reverse the sorted array using reverse method.
1 2 3 4 5 | var colours = ["Blue", "Orange", "White", "Pink"] colours.sort(); colours.reverse(); // Output: ["White", "Pink", "Orange", "Blue"] |
Thank you for reading! Happy Coding!