Typescript - 按降序排序字符串

64

我正在尝试以降序方式对 string[] 进行排序。到目前为止,我所做的是以下代码:

let values = ["Saab", "Volvo", "BMW"]; // example 

values.sort();
values.reverse();

它能够工作,但我正在尝试找出是否有更好的方法来实现。


1
有更好的方法吗?更好的如何?你试图解决什么问题? - user47589
21
这段代码的作用是将一个数组按降序排列。其中,sort() 方法中传入了一个比较函数,该函数通过比较两个元素的大小来确定它们在排序后的位置。具体实现是使用三目运算符判断 a 和 b 的大小关系,从而返回一个负数、0 或正数。在这里,0 - (a > b ? 1 : -1) 返回的值会决定 a 和 b 的位置关系,实现了按照降序排列的效果。 - haim770
2
就像haim所说,提供一个比较函数(请查看数组排序文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)。您可以进行排序并提供比较函数,也许您还可以利用字符串localCompare(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare)。 - riqitang
@haim770 很棒! - gon250
5个回答

104
你需要创建一个比较函数,并将其作为sort函数的参数传递:

你需要创建一个比较函数,并将其作为sort函数的参数传递:

values.sort((one, two) => (one > two ? -1 : 1));

这个 hack 考虑了字符串数组的情况吗? - Memmo
@Memmo 我不确定你在问什么。它将逐个比较字符值。大写字母将排在小写字母前面。 - Thom
我明白。我正在寻找一种将它们与小写字母相同排序的方法,以便不会有大小写差异。 - Memmo
8
在比较它们之前,对它们都调用uppercase()。 - Thom

73
使用String.prototype.localCompare()方法可以获得字符串的数字比较值。
简单示例:
let values = ["Saab", "Volvo", "BMW"];
values.sort((a, b) => b.localeCompare(a))

由于 localCompare 的输出是一个数字,因此这也不会引起 TypeScript 警告。

更多信息和其他函数参数可以在此处查看。


这将无法与 ['9', '75', '72', '64', '61', '60', '6', '59', '57', '56', '54', '53', '52', '5', '47', '46', '44', '42', '41', '40', '4', '3', '26', '25', '22', '21', '20', '2', '19', '17', '16', '14', '13', '12'] 一起使用。 - Viraj Singh
6
要对数字字符串值进行排序,您需要使用values.sort((a, b) => b.localeCompare(a, undefined, {numeric: true})) - David
这是一个比a.toUpperCase() > b.toUpperCase() ? -1 : 1更优雅的解决方案,但在处理非常大的数据集时要小心,尽管localeCompare仍然相当快速,但它大约慢了两倍。 - Branislav Popadič

13

使用以下代码对数组进行升序和降序排序。

const ascending: any= values.sort((a,b) =>  (a > b ? 1 : -1));
const descending: any= values.sort((a,b) => (a > b ? -1 : 1))

0

这是正常的倒序排列

var nums:number[] = [1,2,3,4]
nums.sort((a,b)=> a < b ? 1:-1)
[ 4, 3, 2, 1 ]

如果你需要对自定义对象进行排序,请尝试这个方法。
class Student{
    name:String
    marks:Number
    constructor(name:string, marks:number) {
        this.name = name
        this.marks = marks
    }
}

var students:Array<Student> = [
    new Student("aseem",47),
    new Student("prem",97),
    new Student("john",100)

]

console.log(students.sort( (a,b)=> a.marks > b.marks ? -1:1 ))

会导致按照成绩的倒序排序

/usr/local/bin/node /Users/asee2278/git/mycode/JavaScriptLab/typeScript/concepts/sort.js
[
  Student { name: 'john', marks: 100 },
  Student { name: 'prem', marks: 97 },
  Student { name: 'aseem', marks: 47 }
]


1
社区鼓励在代码旁边添加解释,而不是仅仅提供基于代码的答案(请参见此处)。 - costaparas

0

我所知道的最新库

https://www.npmjs.com/package/ngx-pipes

const numbers = [2, 1, 3];
 
const obj = [
  {id: 4, name: 'Dave', amount: 2},
  {id: 2, name: 'Michael', amount: 2},
  {id: 3, name: 'Dan', amount: 1},
  {id: 1, name: 'John', amount: 1}
];
 
const deepObj = [
  {id: 1, name: 'John', amount: 1337, deep: {prop: 4}},
  {id: 2, name: 'Michael', amount: 42, deep: {prop: 2}},
  {id: 3, name: 'Dan', amount: 1, deep: {prop: 1}},
  {id: 4, name: 'Dave', amount: 2, deep: {prop: 3}}
];

<!-- Returns array ordered by value -->
<p>{{ numbers | orderBy }}</p>  <!-- Output: [1, 2, 3] -->
<p>{{ numbers | orderBy: '-' }}</p>  <!-- Output: [3, 2, 1] -->
 
<!-- Returns array ordered by value of property -->
<p>{{ deepObj | orderBy: 'amount' }}</p>  
<!-- Output: [{id: 3, ...}, {id: 4, ...}, {id: 2, ...}, {id: 1, ...}] -->
<p>{{ deepObj | orderBy: '-amount' }}</p>  
<!-- Output: [{id: 1, ...}, {id: 2, ...}, {id: 4, ...}, {id: 3, ...}] -->
 
<!-- Returns array ordered by value of deep property -->
<p>{{ deepObj | orderBy: 'deep.prop' }}</p>  
<!-- Output: [{id: 3, ...}, {id: 2, ...}, {id: 4, ...}, {id: 1, ...}] -->
<p>{{ deepObj | orderBy: '-deep.prop' }}</p>  
<!-- Output: [{id: 1, ...}, {id: 4, ...}, {id: 2, ...}, {id: 3, ...}] -->
 
<!-- Returns array ordered by mutliple properties -->
<p>{{ obj | orderBy: ['amount', 'id'] }}</p>  
<!-- Output: [{id: 1, ...}, {id: 3, ...}, {id: 2, ...}, {id: 4, ...}] -->

必须以编程方式实现如下

@Component({
  // ..
  providers: [OrderByPipe]
})
export class AppComponent {
  constructor(private orderByPipe: OrderByPipe){
     let values = ["Saab", "Volvo", "BMW"];
     this.orderByPipe.transform(values, '-');
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接