function compare(name, minor) { return function (o, p) { var a, b; if (o && p && typeof o === 'object' && typeof p === 'object') { a = o[name]; b = p[name]; if (a === b) { return typeof minor === 'function' ? minor(o, p) : 0; } if (typeof a === typeof b) { return a < b ? -1 : 1; } return typeof a < typeof b ? -1 : 1; } else { thro("error"); } } }
使用方法
//测试数据
data: [{
name: '李寻欢',
age: 32,
rank: 1
},
{
name: '谢晓峰',
age: 28,
rank: 4
},
{
name: '潇十一郎',
age: 27,
rank: 5
},
{
name: '楚留香',
age: 29,
rank: 3
},
{
name: '傅红雪',
age: 35,
rank: 2
}
]
//先根据rank排序,再根据age排序,最后根据name排序
data.sort(compare('rank', compare('age', compare('name'))));