Sorting an array in JavaScript
Today, we will explain to you how to sorting an array in JavaScript using sort method of the array. Sorting is nothing but lets you arrange data in a required form.
- How to compare two dates in JavaScript
- How to remove duplicates from an Array in JavaScript
- JavaScript Array methods Splice vs Slice
- How to use Map, Filter, and Reduce in JavaScript
- Set a default parameter value for a JavaScript function
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.
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.
var numbers = [84,45,7,0,17,34,28]
numbers.sort();
// Output: [0, 17, 28, 34, 45, 7, 84]
- 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.
The below example describes how to sort the array in ascending order.
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.
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.
var colours = ["Blue", "Orange", "White", "Pink"]
colours.sort();
colours.reverse();
// Output: ["White", "Pink", "Orange", "Blue"]
Thank you for reading! Happy Coding!