如何为javascript排序函数制作一个高效的比较器来对字符串数组进行排序

How to make a efficient comparator for javascript sort function for sorting an array of strings?

本文关键字:排序 比较器 高效 字符串 数组 一个 函数 javascript 数制      更新时间:2023-09-26

我有一个字符串数组,看起来像:

array = ['third', 'first', 'fourth', 'second', 'custom2', 'custom1']

我想对这个数组进行排序,所以它看起来像:

array = ['first', 'second', 'third', 'fourth', 'custom2', 'custom1']

特定字符串,如"第一个"、"第二个"应该按给定的顺序排序(第一个在第二个之前第三个…),任何其他字符串都应该按任意顺序附加在末尾。一个只包含这些字符串子集的数组应该按正确的顺序排序:

['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"
]

或者,更好的是,使用施瓦茨变换:

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]
})