Last active
September 7, 2017 07:54
-
-
Save simplelife7/d8c2b9716f70421e6a43 to your computer and use it in GitHub Desktop.
【JS】根据数组里的对象集合的某个字段对数组进行排序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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