如何以唯一顺序对数组进行排序 [英] How to sort an array in a unique order

查看:416
本文介绍了如何以唯一顺序对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数组:

var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

我想输出这个列表,比如说,下拉列表。我希望首先显示紧急,然后显示提醒。其余部分应按字母顺序排序。

I want to output this list in say, a dropdown. I want 'Urgent' to show up first, followed by 'Alert'. The rest should be sorted alphabetically.

我知道我可以按字母顺序对整个数组进行排序 myList.sort()但有没有办法根据我的独特要求对此列表进行排序?我希望这可以作为数组完成而不将其转换为对象并分配优先级标识符 - 但我可能错了。

I'm aware I can alphabetically sort the entire array with myList.sort() but is there a way to sort this list to my unique requirements? I'm hoping this can be done as an array without converting it to an object and assigning priority identifiers - but I may be wrong.

此外,如果紧急或警报不存在?

Also, what if Urgent or Alert doesn't exist?

编辑:这是我尝试过的: https://jsfiddle.net/reala/rqacrz0k/

EDIT: Here is what I tried: https://jsfiddle.net/reala/rqacrz0k/

推荐答案

您可以使用对象作为排序顺序。

You could use an object for the sort order.

var array = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

array.sort(function (a, b) {
    var order = { Urgent: -2, Alert: -1 };
    return (order[a] || 0) - (order[b] || 0) || a.localeCompare(b);
});

console.log(array);

这篇关于如何以唯一顺序对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆