虽然数组可以直接用sort()一键排序,但这排序是默认将数组元素转换为字符串,然后按照字符的Unicode码顺序进行排序。
但如果我要做特定的排序呢?
现有一个数组list
[
{
priority:'Critical',
Others:[]
},
{
priority:'Severe',
Others:[]
}
]
需求是一定要按Severe, Crtical的顺序排序。两种解决方法:
1. 用原始sort()
const priorityOrder = ['Critical', 'Severe'];
list.sort((a, b) => {
return priorityOrder.indexOf(a.priority)-priorityOrder.indexOf(b.priority);
});
2. 用lodash的_.sort()
const priorityOrder = ['Critical', 'Severe'];
list = _.sortBy(list, [(item) => priorityOrder.indexOf(item.priority)]);