An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
.sort() Method | JavaScript
Array.prototype.sort()
Simply put, .sort()
, sorts elements of an array, by default it sorts values in alphabetical and ascending order.
We can use this without any parameters for simple string and number sorting.
Remember: .sort()
method mutates the original array!
String Example:
const profs = ['Robert', 'Tony', 'Vladamir', 'Adam', 'Steve'];profs.sort();console.log(profs);Output: [ 'Adam', 'Robert', 'Steve', 'Tony', 'Vladamir' ]
Number Example:
const numbers = [20, 33, 54, 100, 205];numbers.sort();console.log(numbers);Output: [ 100, 20, 205, 33, 54 ]
There is a flaw in the sort method, why did 100 come before the rest of these numbers?
The method is converting the elements to strings and comparing them in UTF-16 code units.
That is why "100" is being put at the front of the array, and the same goes for "205" being in the middle of the array.
To fix this error in sorting, we can use the compare function
.
function(a, b){return a - b}
When the .sort()
method is comparing our two values (a, b)
, it sorts the values in accordance to whats returned.
It will return either a negative, a positive or a zero.
If it returns a value < than 0 then
a
is sorted beforeb
If it returns a value > than 0, then
b
is sorted beforea
If it returns a value = 0, the sort order does not change.
Compare Function Example:
const numbers = [20, 33, 54, 100, 205]numbers.sort(function(a, b) { return a - b});console.log(numbers)Output: [ 20, 33, 54, 100, 205 ]
In ES6, we can also do this using an arrow function expression.
let numbers = [20, 33, 54, 100, 205]numbers.sort((a, b) => a - b);console.log(numbers);Output: [ 20, 33, 54, 100, 205 ]
Reversing a Sorted List
If we ever need to reverse out sorted array all we need to do is switch a - b
to b - a
!
let numbers = [20, 33, 54, 100, 205]numbers.sort((a, b) => a-b);console.log(numbers);Output: [ 205, 100, 54, 33, 20 ]
Reverse using .reverse()
Although this method is not recommended because it could lead to unexpected results, it is an easy way to reverse your list.
let numbers = [20, 33, 54, 100, 205]numbers.sort((a, b) => a - b).reverse();console.log(numbers);Output: [ 205, 100, 54, 33, 20 ]
In Conclusion
There are many ways of working with the .sort()
method, but these basics should help you get a good understanding of how the method works.
To learn about more complex uses of this method, check out this fantastic video!
Original Link: https://dev.to/tibeta/sort-method-javascript-488a
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To