首页 > 代码库 > 根据对象中某个属性值对其进行排序

根据对象中某个属性值对其进行排序

var array = [    {name: ‘a‘, hp: 100},    {name: ‘b‘, hp: 2},    {name: ‘d‘, hp: 3},    {name: ‘m‘, hp: 7},        {name: ‘c‘, hp: 4},    {name: ‘e‘, hp: 4}]array.sort(getSortFun(‘desc‘, ‘hp‘));function getSortFun(order, sortBy) {    var ordAlpah = (order == ‘asc‘) ? ‘>‘ : ‘<‘;    var sortFun = new Function(‘a‘, ‘b‘, ‘return a.‘ + sortBy + ordAlpah + ‘b.‘ + sortBy + ‘?1:-1‘);    return sortFun;}alert(JSON.stringify(array.slice(0, 3)));

 

根据对象中某个属性值对其进行排序