使用特殊字符按升序和降序对数组进行排序

时间:2018-02-13 09:13:03

标签: javascript

我正在尝试对包含特殊字符(德语)的数组进行排序。这是表的排序函数,因此我有一些具有true / false值的列。我已经编写了一个用于排序的函数,它适用于升序,真/假顺序但不适用于降序。

return sortItems.sort((a, b) => {
    const firstItem = (typeof a[options.field] === 'string')
        ? a[options.field].toLowerCase()
        : a[options.field];

    const secondItem = (typeof b[options.field] === 'string')
        ? b[options.field].toLowerCase()
        : b[options.field];

    if (firstItem < secondItem) {
        if (typeof firstItem === 'string') {
            if (firstItem.localeCompare(secondItem) < secondItem.localeCompare(firstItem)) {
                return (options.asc) ? -1 : 1;
            } else if (firstItem.localeCompare(secondItem) > secondItem.localeCompare(firstItem)) {
                return (options.asc) ? 1 : 1;
            }
        } else {
            return (options.asc) ? -1 : 1;
        }
    } else if (firstItem > secondItem) {
        if (typeof firstItem === 'string') {
            if (firstItem.localeCompare(secondItem) < secondItem.localeCompare(firstItem)) {
                return (options.asc) ? -1 : 1;
            } else if (firstItem.localeCompare(secondItem) > secondItem.localeCompare(firstItem)) {
                return (options.asc) ? 1 : 1;
            }
        } else {
            return (options.asc) ? 1 : -1;
        }
    }
    return 0;
});

感谢任何帮助。

0 个答案:

没有答案