[嗨,我正在尝试在JavaScript中实现自定义字符串比较器功能。我希望某些特殊值始终位于其他值之前,其余的仅按字母顺序排序。例如,如果我有一个数组(“非常重要”和“重要”)是两个特殊值。
["e","c","d","Very Important","a",null,"Important","b","Very Important"].
排序后,数组应该是(如果存在null或未定义的值,则需要放在最后)
["Very Important", "Very Important", "Important", "a","b","c","d","e",null]
如何为上述要求编写比较器功能?
非常感谢
您可以
null
值移到底部,'Very Important'
字符串移到顶部,然后var array = ["e", "c", "d", "Very Important", "a", null, "Important", "b", "Very Important"];
array.sort((a, b) =>
(a === null) - (b === null) ||
(b === 'Very Important') - (a === 'Very Important') ||
a > b || -(a < b)
);
console.log(...array);
您可以尝试以下操作:
const array = ["e","c","d","Very Important","a",null,"Important","b","Very Important"];
const importantElems = ['Very Important', 'Important'];
const lastElems = [null, undefined];
const firstPart = array.filter(e => importantElems.includes(e));
const middlePart = array.filter(e => !importantElems.includes(e) && !lastElems.includes(e))
.sort((a,b) => a.localeCompare(b));
const lastPart = array.filter(e => lastElems.includes(e));
const result = firstPart.concat(middlePart).concat(lastPart);
console.log(result);
我希望有帮助!