0

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?

0

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.