如何对这样的数组进行排序:
['apple','very','auto','tom','tim','violet'....]
要按 v、a、t、x、b...等排序(不按字母顺序)
['violet','very','auto','tom','tim',...]
在脚本中,我会做这样的事情:
myArray.sort('v','a','t'...)
我怎样才能用 JavaScript 做到这一点?
您可以维护字母优先级的数组sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort通过该数组中第一个字母的索引。
此版本将任何输入not从排序数组末尾的有序字符之一开始,按常规(区域设置敏感)字母顺序:
var order = ['v','a','t'];
var input = ['violet', 'EXTRA 2', 'very','auto','tom','tim', 'EXTRA 1'];
input.sort(function(a, b) {
// are the strings equal?
if(a === b) {
return 0;
}
// if they are not equal, compare the first letters
// against the custom sort order
var indexOfA = order.indexOf(a[0]);
var aInList = indexOfA >= 0;
var indexOfB = order.indexOf(b[0]);
var bInList = indexOfB >= 0;
// if the first letter of neither string is in the list,
// compare alphabetically
if(!aInList && !bInList) {
return a.localeCompare(b);
} else if(!aInList) {
// the first letter of only a is not in the list
return 1;
} else if(!bInList) {
// the first letter of only b is not in the list
return -1;
} else if(indexOfA === indexOfB) {
// the first letter of a and b are both in the list
// and they are the same
return a.localeCompare(b);
} else {
// the first letters are different; sort by first letter
return indexOfA - indexOfB;
}
})
如果您可以保证第一个字母位于排序顺序数组中,则可以省略if(indexOfX === -1)
checks.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)