Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Sort strings descending

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.

like image 259
gon250 Avatar asked Nov 07 '16 18:11

gon250


People also ask

How do you sort in descending order in TypeScript?

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.

How do I sort in ascending order TypeScript?

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.

How do I sort objects in TypeScript?

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.


2 Answers

You need to create a comparison function and pass it as a parameter of sort function:

values.sort((one, two) => (one > two ? -1 : 1)); 
like image 81
Thom Avatar answered Sep 28 '22 04:09

Thom


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

like image 43
David Avatar answered Sep 28 '22 05:09

David