I'm trying to sort a string[]
in descending way. So far what I have done is the code below:
let values = ["Saab", "Volvo", "BMW"]; // example values.sort(); values.reverse();
It's working but I'm trying to figure out if there is a better way to do it.
To sort an array of strings in descending order: Call the sort() method passing it a function. The function will be called with 2 elements from the array.
Use the sort() Method to Sort Array in TypeScript The sort() method returns the result in ascending order by default. The array type is to be defined as string[] . The sort() method returns the string array, and the array elements are given in alphabetical order as an output.
Array. sort() function sorts an Array. The Sort() function will sort array using the optional compareFunction provided, if it is not provided Javascript will sort the array object by converting values to strings and comparing strings in UTF-16 code units order.
You need to create a comparison function and pass it as a parameter of sort function:
values.sort((one, two) => (one > two ? -1 : 1));
A more current answer is that you can utilize String.prototype.localCompare() to get a numeric comparison value
Simple example:
let values = ["Saab", "Volvo", "BMW"]; values.sort((a, b) => b.localeCompare(a))
This also wont causes TypeScript warnings as the output of localCompare
is a number
More info and additional function parameters can be seen here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With