JavaScript:排序异常

JavaScript: Sorting with exception

本文关键字:异常 排序 JavaScript      更新时间:2023-09-26

假设我有一个对象数组(为了更简单的显示目的,我只将其显示为数组)

[ 'TEST', 'NEW', 'ALPHA', 'ZOO', 'WHATEVER' ]

我需要按字母顺序对它进行排序(简单部分),然而,我需要以一种方式对它进行分类,即某个单词,比如NEW,将在最后结束。

[ 'ALPHA', 'TEST', 'WHATEVER', 'ZOO', 'NEW' ]

这是我用排序的函数

var sortedWords = function(a, b) {
    return a.word > b.word ? 1 : -1 ;
};

因此,我得到sortedWords数组,然后再次遍历它,创建另一个数组并将单词推入新数组,除非单词等于NEW。在这种情况下,我把它放在一边,并在返回它之前将其附加在这个新数组的最后。必须有一种更好、更有效的方法来做到这一点。

谢谢。

更改比较器以首先查找NEW

function (a, b) {
    if ((a.word === 'NEW') != (b.word === 'NEW')) {
        return a.word === 'NEW' ? 1 : -1;
    }
    return a.word > b.word ? 1 :
           a.word < b.word ? -1 : 0;
}

使用带有自定义compareFunction 的排序

var ar = [ 'ALPHA', 'WHATEVER', 'NEW', 'ZOO', 'TEST' ];
ar.sort(function(a, b){
    var wordToBeLast = 'NEW';  // set your word here
    if(a===wordToBeLast){
        return 1;
    } else if(b===wordToBeLast){
        return -1;
    } else {
        return a > b; 
    }
});

您可以如下定义比较器函数:

var sortedWords = function(a, b) {
    if (a.word === b.word) {
        // a and b are considered equal, the order is okay
        return 0;   
    }
    if (a.word === "NEW") {
        // "NEW" is considered larger than every other value, the order is wrong
        return 1;
    }
    // Correct order if b equals "NEW", otherwise lexicographical comparison
    return b.word === "NEW" ? -1 : (a.word > b.word ? 1 : -1);
};

使用lodash有一种更简单的方法,它可以扩展到更复杂的场景,同时保持代码的简单性。

const strings = [ 'TEST', 'NEW', 'ALPHA', 'ZOO', 'WHATEVER' ];
_.sortBy(strings, [
    (string) => string !== 'NEW',
    (string) => string
  ])