您好,我正在尝试在 JavaScript 中实现自定义字符串比较器函数。有一些特殊的值,我希望它们总是在其他值之前,其余的只是按字母顺序排序。 例如,如果我有一个数组 ("very important""important", "Less important") 是三个特殊值(应该有上面的顺序)
["e","c","Less Important","d","Very Important","a",null,"Important","b","Very Important"].
排序后的数组应该是(如果有null或undefined值,需要放在最后)
["Very Important", "Very Important", "Important", "Less Important" "a","b","c","d","e",null]
如何为上述要求编写一个比较器函数? (我使用库的比较器 api,所以我无法对数组进行排序,但需要使用比较器实现逻辑(如 java 中的 compareTo,它返回 0,1,-1)
非常感谢
最佳答案
你可以
- 将
null
值移到底部, - 将
'Very Important'
字符串移到顶部, - 将
Important'
字符串移至顶部并 - 将其余的升序排序。
var array = ["Important", "e", "c", "d", "Very Important", "a", null, "b", "Very Important"];
array.sort((a, b) =>
(a === null) - (b === null) ||
(b === 'Very Important') - (a === 'Very Important') ||
(b === 'Important') - (a === 'Important') ||
a > b || -(a < b)
);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于JavaScript 字符串数组自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216997/