Search code examples
javascriptsortingcolumnsorting

Send column index to sort function


Here is a function sorting 2d array by first column.

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;
    }
}

How to send a column index to function instead of hardcoded 0?


Solution

  • May be you can try to use currying:

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

    So usage would be something like

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