如何使Lodash orderBy函数与重音字符一起使用?

时间:2017-06-24 20:17:55

标签: javascript lodash

有没有办法让Lodash的orderBy函数支持重音字符?

与á,é,ñ等相似。执行排序时,这些会移动到数组的末尾。

2 个答案:

答案 0 :(得分:1)

默认情况下,它听起来不使用localeCompare。这令人惊讶。

您可以转换为数组(如果需要),然后将sortlocaleCompare一起使用:

theArray.sort(function(a, b) { return a.localeCompare(b); });

答案 1 :(得分:0)

我通过比较消毒元素来解决它。

theArray.sort(function(a, b) {
    return a.toLowerCase().removeAccents().localeCompare(b.toLowerCase().removeAccents());
});

removeAccents函数:

String.prototype.removeAccents = function () {
return this
    .replace(/[áàãâä]/gi,"a")
    .replace(/[éè¨ê]/gi,"e")
    .replace(/[íìïî]/gi,"i")
    .replace(/[óòöôõ]/gi,"o")
    .replace(/[úùüû]/gi, "u")
    .replace(/[ç]/gi, "c")
    .replace(/[ñ]/gi, "n")
    .replace(/[^a-zA-Z0-9]/g," ");
}