typescript 打字稿 - 对字符串进行降序排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40472548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript - Sort strings descending
提问by gon250
I'm trying to sort a string[]
in descendingway. So far what I have done is the code below:
我想排序string[]
在递减的方式。到目前为止,我所做的是下面的代码:
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.
它正在工作,但我试图弄清楚是否有更好的方法来做到这一点。
回答by Thom
You need to create a comparison function and pass it as a parameter of sort function:
您需要创建一个比较函数并将其作为排序函数的参数传递:
values.sort((one, two) => (one > two ? -1 : 1));
回答by Dve
A more current answer is that you can utilize String.prototype.localCompare() to get a numeric comparison value
一个更当前的答案是你可以利用 String.prototype.localCompare() 来获得一个数字比较值
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
这也不会导致 TypeScript 警告,因为输出localCompare
是一个数字
More info and additional function parameters can be seen here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
更多信息和附加功能参数可以在这里看到https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
回答by Sheo Dayal Singh
Use the following code to sorting the Array in ascending and descending order.
使用以下代码按升序和降序对 Array 进行排序。
const ascending: any= values.sort((a,b) => (a > b ? 1 : -1));
const descending: any= values.sort((a,b) => (a > b ? -1 : 1))