[英]How to sort an array in a unique order
Given an array: 给定一个数组:
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.
其余应按字母顺序排序。
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? 我知道我可以使用
myList.sort()
按字母顺序对整个数组进行排序,但是有没有办法根据我的独特需求对这个列表进行排序? 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? 另外,如果不存在紧急或警报该怎么办?
EDIT : Here is what I tried: https://jsfiddle.net/reala/rqacrz0k/ 编辑 :这是我尝试过的: https : //jsfiddle.net/reala/rqacrz0k/
It's best if you keep your prioritized elements separate from the main list, if you can't guarantee they will be present. 最好将优先元素与主列表分开,如果不能保证它们会出现。 I would filter those elements out, sort the rest, and concatenate the results with your special list.
我将筛选出这些元素,对其余元素进行排序,然后将结果与您的特殊列表连接起来。
var special = ["Urgent","Alert"]; var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ]; myList = special.concat(myList.filter(function(el){ return special.indexOf(el) == -1; }).sort()); alert(myList);
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);
You could use filter to get the special values, sort the rest, and concatenate the parts: 您可以使用过滤器来获取特殊值,对其余值进行排序,然后将各个部分连接起来:
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ]; myList = myList.filter( v => v === 'Urgent' ).concat( myList.filter( v => v === 'Alert' ), myList.filter( v => !['Alert','Urgent'].includes(v) ).sort()); console.log(myList);
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ]; console.log(['Urgent', 'Alert', ...myList.filter(item => item !== 'Urgent' && item !== 'Alert').sort()]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.