My current JavaScript Array Sorting code gets the job done, but it feels inefficient.
For example, I have an array of objects structured like this:
dummyData = [];
dummyData.push({ col01:"aa", col02:"ac", col03:"ab" });
dummyData.push({ col01:"ab", col02:"ab", col03:"ac" });
dummyData.push({ col01:"ac", col02:"aa", col03:"aa" });
To sort this array based on col01, I use the following function:
function f_sort_col01(dataArg) {
dataArg.sort(function(res01, res02) {
var arg01 = res01.col01.toLowerCase();
var arg02 = res02.col01.toLowerCase();
if(arg01 < arg02) { return -1; }
if(arg01 > arg02) { return 1; }
return 0;
});
return dataArg;
}
While this approach works, it requires creating a new function for each column we want to sort on, like f_sort_col02 for col02:
function f_sort_col02(dataArg) {
dataArg.sort(function(res01, res02) {
var arg01 = res01.col02.toLowerCase();
var arg02 = res02.col02.toLowerCase();
if(arg01 < arg02) { return -1; }
if(arg01 > arg02) { return 1; }
return 0;
});
return dataArg;
}
It would be more efficient if we could generalize the sorting function to accept the column name as a parameter, like this:
function f_sort(dataArg, colName) {
dataArg.sort(function(res01, res02) {
var arg01 = res01[colName].toLowerCase();
var arg02 = res02[colName].toLowerCase();
if(arg01 < arg02) { return -1; }
if(arg01 > arg02) { return 1; }
return 0;
});
return dataArg;
}
This way, we can specify the column name when calling the function, making the sorting process more flexible.