Skip to content

Instantly share code, notes, and snippets.

@dontcry2013
Created March 1, 2019 03:12
Show Gist options
  • Save dontcry2013/22e0b0e657d45469ca4564b92a3ee03e to your computer and use it in GitHub Desktop.
Save dontcry2013/22e0b0e657d45469ca4564b92a3ee03e to your computer and use it in GitHub Desktop.
JS SORT
var tempDataArray2 = [
"1|112|223|119|23",
"2|212|123|119|23",
"1|212|223|119|23",
"3|2|223|119|23",
"3|1|2233|119|25",
"3|1|2233|119|23",
"3|1|223|119|23",
];
var tempDataArray3 = [];
for(var i = 0;i<tempDataArray2.length;i++){
var tmp = tempDataArray2[i];
var tmp2 = tmp.split("|");
tempDataArray3.push(tmp2)
}
console.log(tempDataArray3);
// 存储排序后的数据
var currentData = [];
// 排序数组,支持多列排序
//var orderArr = [{colName:"age",orderDir:"asc"},{colName:"name",orderDir:"desc"}];
var orderArr = ["asc","asc","desc","asc","desc"];
// 生成排序脚本
var sortData = _generateByStr(orderArr,1);
currentData = tempDataArray3.concat();
// 生成多列排序字符串方法
function _generateByStr(tempDataArray,times) {
var arr = tempDataArray.concat();
if (arr == null || arr.length == 0) {
return "";
} else {
console.log(arr.length)
if (arr.length > 1) {
var a = arr[0];
arr.shift();
return "_sortBy('" + times + "','" + a + "',"
+ _generateByStr(arr,++times) + ")";
} else {
return "_sortBy('" + times + "','"
+ a + "')";
}
}
}
// 排序主方法
function _sortBy(name, dir, minor) {
return function(o, p) {
console.log(o,p)
var a, b;
if (o && p && typeof o === 'object' && typeof p === 'object') {
a = o;
b = p;
if (a === b) {
return typeof minor === 'function' ? minor(o, p) : 0;
}
if (typeof a === typeof b) {
if (dir == "asc") {
return a < b ? -1 : 1;
} else {
return a > b ? -1 : 1;
}
}
if (dir == "desc") {
return typeof a < typeof b ? -1 : 1;
} else {
return typeof a > typeof b ? -1 : 1;
}
} else {
throw("error");
}
};
}
console.log(sortData)
console.log(currentData.sort(eval(sortData)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment