We are tasked with creating a function that can take an unlimited number of arguments to sort an array by.
For example:
var data = [['John','London',35],
['Ricky','Kuala Lumpur',38],
['Ivan','Moscow,29]];
function arrangeOrder(a,b) {
//Sort by field [0]
if (a[0] > b[0]) return 1;
if (a[0] < b[0]) return -1;
//Sort by field [1]
if (a[1] > b[1]) return 1;
if (a[1] < b[1]) return -1;
//Sort by field [2]
if (a[2] > b[2]) return 1;
if (a[2] < b[2]) return -1;
}
data.sort(arrangeOrder);
It works perfectly! However, the content of data
and the number of fields can vary, as well as the fields and the number of fields by which the data needs to be sorted. So, what I need is a way to specify the function like this:
data.sort(arrangeOrder(1,3,6,9,2));
I have found a way to add ONE parameter:
function propComparator(prop) {
return function(a,b){
return a[prop] - b[prop];
}
}
data.sort(propComparator(prop));
And also a way to handle an undefined number of arguments for the function using the arguments
object:
function foo() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
But I am struggling to combine these techniques. It seems like it should be possible, but perhaps I lack the necessary skill.
NOTE: ES6 solutions are not compatible with my environment, so I require vanilla JavaScript! I appreciate any assistance I can get!