varby=function(name){returnfunction(o, p){var a, b;if(typeof o ==="object"&&typeof p ==="object"&& o && p){ a = o[name]; b = p[name];if(a === b){return0;}if(typeof a ===typeof b){return a < b ?-1:1;}returntypeof a <typeof b ?-1:1;}else{throw("error");}}}var employees=[{name:"George", age:32, retiredate:"March 12, 2014"},{name:"Edward", age:17, retiredate:"June 2, 2023"},{name:"Christine", age:58, retiredate:"December 20, 2036"},{name:"Sarah", age:62, retiredate:"April 30, 2020"}]employees.sort(by("age"));
console.log(employees);
根據(jù)多個字段排序
varby=function(name,minor){returnfunction(o,p){var a,b;if(o && p &&typeof o ==='object'&&typeof p ==='object'){a = o[name];b = p[name];if(a === b){returntypeof minor ==='function'?minor(o,p):0;}if(typeof a ===typeof b){return a < b ?-1:1;}returntypeof a <typeof b ?-1:1;}else{throw("error");}}}employees.sort(by('age',by('name')));
console.log(employees);