要按状态(字符串值)对 TypeScript 列表进行排序,可以使用sort()
方法和自定义的比较函数。下面是一个示例代码:
interface Item {
name: string;
status: string;
}
const items: Item[] = [
{ name: 'Item 1', status: 'active' },
{ name: 'Item 2', status: 'inactive' },
{ name: 'Item 3', status: 'pending' },
{ name: 'Item 4', status: 'active' },
{ name: 'Item 5', status: 'inactive' },
];
function compareStatus(a: Item, b: Item) {
if (a.status < b.status) {
return -1;
}
if (a.status > b.status) {
return 1;
}
return 0;
}
items.sort(compareStatus);
console.log(items);
在上面的示例中,我们定义了一个Item
接口来表示每个列表项的结构。然后,我们创建了一个items
数组来保存所有的列表项。
接下来,我们定义了一个compareStatus
函数作为比较函数。该函数接受两个参数a
和b
,表示需要比较的两个列表项。比较函数根据列表项的status
属性进行比较,如果a
的status
小于b
的status
,则返回-1,如果a
的status
大于b
的status
,则返回1,如果两个status
相等,则返回0。
最后,我们使用sort()
方法对items
数组进行排序,传入我们定义的比较函数compareStatus
作为参数。排序后,我们打印出排序后的items
数组。
运行上述代码,将按照状态(字符串值)对items
数组进行排序,并打印排序后的结果。
上一篇:按状态转换数据数组