首页 > 解决方案 > 发送列索引到排序函数

问题描述

这是一个按第一列对二维数组进行排序的函数。

var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];

console.log(a.sort(sortFunction,100));

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return c;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}

如何将列索引发送到函数而不是硬编码 0?

标签: javascriptsortingcolumnsorting

解决方案


也许你可以尝试使用柯里化:

sortFunction = index => (a, b) => {
    if (a[index] === b[index]) {
        return 0;
    }
    else {
        return (a[index] < b[index]) ? -1 : 1;
    }
}

所以用法会像

console.log(a.sort(sortFunction(1)));


推荐阅读