发布于 4年前

js 根据对象中的某个属性值来进行排序

/**
 * 根据对象中的某个属性值来进行排序
 * @param {*} property  属性值
 * @param {*} type      排序方式 down:降序;默认升序
 */
function compareSort(property, type) {
  return function (a, b) {
    let value1 = a[property];
    let value2 = b[property];
    let result = type === 'down' ? value2 - value1 : value1 - value2;

    return result;
  };
}

/**
 * 示例
 */

let arr = [
    { id: 1, name: '西瓜', price: 5 },
    { id: 2, name: '苹果', price: 3 },
    { id: 3, name: '山竹', price: 8 },
    { id: 4, name: '桔子', price: 2 }
];

let res = arr.sort(compareSort('price'));
// res =  [
//    { id: 3, name: '桔子', price: 2 },
//    { id: 2, name: '苹果', price: 3 },
//    { id: 1, name: '西瓜', price: 5 },
//    { id: 3, name: '山竹', price: 8 }
// ];
©2020 edoou.com   京ICP备16001874号-3