Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Last active September 7, 2017 07:54
Show Gist options
  • Save simplelife7/d8c2b9716f70421e6a43 to your computer and use it in GitHub Desktop.
Save simplelife7/d8c2b9716f70421e6a43 to your computer and use it in GitHub Desktop.
【JS】根据数组里的对象集合的某个字段对数组进行排序
var arr = [
{name:'hdj', age:28},
{name:'yim', age:25},
{name:'hdq', age:26},{name:'hdq', age:22},{name:'hdq', age:555},{name:'hdq', age:1111},{name:'hdq', age:99}
];
function arrSortByField(arr, field,order,primer){
var order = (order == undefined) ? 1 : ((order == 'asc') ? 1 : -1) ;
var primer = primer || parseInt;
var sortFunc = function(field,reverse,primer){
return function (a, b) {
var a = a[field];
var b = b[field];
if (typeof (primer) != 'undefined') {
a = primer(a);
b = primer(b);
}
if (a < b) return reverse * -1;
if (a > b) return reverse * 1;
return 0;
}
}
return arr.sort(sortFunc(field,order,primer))
}
arrSortByField(arr,'age');
arrSortByField(arr,'age','asc');//asc为升序,des为降序
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment