I want to create a function that sorts an json object by two keys which I pass to function as arguments as shown below:
function sort_json_key1_then_key2(jsonObj, key_1, key_2) {
jsonObj.sort(function(a, b) {
if (a.key_1 == b.key_1) {
return a.key_2 == b.key_2 ? 0 : +a.key_2 > +b.key_2 ? 1 : -1;
}
return +a.key_1 > +b.key_1 ? 1 : -1;
});
}
Take the below json object as example:
var obj = [
{"cl":"8","fare":"500.0","name":"41"},
{"cl":"7","fare":"200.0","name":"37"},
{"cl":"10","fare":"200.0","name":"33"},
{"cl":"9","fare":"500.0","name":"29"},
{"cl":"6","fare":"500.0","name":"29"}
];
I call the function to sort by 'fare' then 'cl' as follows:
var sorted = sort_json_key1_then_key2(obj, 'fare', 'cl');
var json_string = JSON.stringify(sorted);
console.log(json_string);
But I get 'undefined' as output in console. I think I am not correctly passing the keys as arguments to function correctly. Any idea on how to solve this?