I have a 2D array and I'm using a custom sort function to sort it by column. My code structure is similar to this:
function sortBy(array, primaryCol, secondaryCol) {
function compareNumber(a, b) {
if (a[primaryCol] == b[primaryCol]) {
return a[secondaryCol] - b[secondaryCol] ? -1 : 1;
}
return a[primaryCol] - b[primaryCol];
}
array.sort(compareNumber);
}
sortBy(colors, 3, 0);
Inside the compareNumber function, I'm accessing primaryCol and secondaryCol parameters of the sortBy function. What I want to do is move compareNumber function outside of sortBy. In that case, the code won't work, because compareNumber can't access primaryCol and secondaryCol. Also passing primaryCol and secondaryCol to compareNumber function doesn't do any good, because I guess it takes only two arguments.
function compareNumber(a, b, primaryCol, secondaryCol) {
if (a[primaryCol] == b[primaryCol]) {
return a[secondaryCol] < b[secondaryCol] ? -1 : 1;
}
return a[primaryCol] - b[primaryCol];
}
function sortBy(array, primaryCol, secondaryCol) {
array.sort(compareNumber, primaryCol, secondaryCol);
}
sortBy(colors, 3, 0);
So, is there any way to make this work, pass additional arguments to sort function other than a and b?