<script>
var sort_arry1 = [
{"num": 1},
{"num": 7},
{"num": 3},
{"num": 2},
];
var sort_arry2 = [
{"num": 1},
{"num": 7},
{"num": 3},
{"num": 2},
];
var compare = function (json_key,reverse=false) {
return function (obj1, obj2) {
var return_num = 0;
var val1 = obj1[json_key];
var val2 = obj2[json_key];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return_num = -1;
} else if (val1 > val2) {
return_num = 1;
}
if(reverse){
return -return_num
}
else{
return return_num
}
}
};
sort_arry1 = sort_arry1.sort(compare("num"));
console.log(sort_arry1);
sort_arry2 = sort_arry2.sort(compare("num",true));
console.log(sort_arry2);
</script>
结果
网友评论