我有一个字符串数组,如下所示:
array = ['third', 'first', 'fourth', 'second', 'custom2', 'custom1']
我想对这个数组进行排序,所以它看起来像:
array = ['first', 'second', 'third', 'fourth', 'custom2', 'custom1']
特定字符串如'first'、'second'、...应按给定顺序排序(第一个、第二个、第三个...),任何其他字符串应附加在末尾以任意顺序。无论如何,仅包含这些字符串子集的数组应该按正确的顺序排序:
['fourth', 'something', 'second'] => ['second', 'fourth', 'something']
我想知道是否有可能为 javascript sort() 函数编写一个比较器函数来有效地解决这个问题。
最佳答案
类似这样的东西吗?
array = ['third', 'first', 'fourth', 'second', 'custom2', 'custom1']
special = ['first', 'second', 'third', 'fourth']
array.sort(function(a, b) {
var ia = special.indexOf(a)
var ib = special.indexOf(b)
if(ia >= 0 && ib >= 0) return ia - ib;
if(ia >= 0) return -1;
if(ib >= 0) return +1;
return a > b ? 1 : a == b ? 0 : -1;
})
console.log(array)
[
"first",
"second",
"third",
"fourth",
"custom1",
"custom2"
]
或者,更好的是,使用 schwartzian transform :
a = array.map(function(x) {
var n = special.indexOf(x);
return [n < 0 ? array.length : n, x]
}).sort(function(a, b) {
return (a[0] - b[0]) || (a[1] > b[1] ? 1 : a[1] == b[1] ? 0 : -1);
}).map(function(x) {
return x[1]
})
关于javascript - 如何为 javascript 排序函数制作一个有效的比较器来对字符串数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17420773/