array with objects sort

实现对象作为数组元素排序的方法

需求:现有一个数组,每一项包含折扣信息与过期时间,现要求先按照折扣大小进行升序排序,然后相同折扣的,按照过期时间进行降序排序。

分析

  1. 数组类型的排序可以使用Array.prototype.sort函数的排序算法(也可以自己实现排序算法,这里不做讨论);

  2. 查看Array.prototype.sort文档发现该函数接受一个compare函数作为参数,sort函数内部借助该函数的返回值对数组进行排序;

    而compare函数从sort函数内部接受两个数组元素(记为a与b)作为参数且一共有3种返回值:

    • -1,表示a的Unicode位点小于b,a调到b前面。
    • 0,表示a的Unicode位点等于b,a与b的位置不变。
    • 1,表示a的Unicode位点大于b,a调到b后面。

    经过测试发现该compare函数的执行次数与使用者规定的排序规则有关。若数组当前的顺序越符合该规则,那么执行次数越少,否则执行次数越多。

  3. 动手实现一个compare函数作为Array.prototype.sort函数的参数;(其实就是编写排序规则)

排序规则

数组根据数组元素的折扣与过期时间属性进行排序,且折扣的权重大于过期时间。

代码实现

const ASC = -1;//降序
const DES = 1;//升序
function compare(a, b, property, sort) {
    if(!(property in a) || !(property in b )) return 0;
    if(a[property] < b[property]) return sort;
    if(a[property] > b[property]) return -sort;
    return 0;
}
function sort(arr, properties = [], order = ASC) {
    //参数合法性判断...
    
    //方法实现
    return arr.sort((a, b) => {
        for(var i = 0; i < properties.length; i++) {
            const result = compare(a, b, properties[i], order);
            if(result !== 0) return result; //若第一权重的属性不相同,则直接返回结果,否则比较第二权重的属性。
        }
        return 0; 
    });
}

验证

var list = [
        {
        "discountValue": "1",
        "expireTime": 1542247259
        },
        {
          "discountValue": "5",
          "expireTime": 1542247257
        },
        {
          "discountValue": "3",
          "expireTime": 1542247253
        },
        {
          "discountValue": "1",
          "expireTime": 1542247251
        },
        {
          "discountValue": "3",
          "expireTime": 1542247253
        },
        {
          "discountValue": "3",
          "expireTime": 1542247252
        },
      ];
      
sort(list, ['discountValue', 'expireTime']);

//预期结果:[{"discountValue":"1","expireTime":1542247251},{"discountValue":"1","expireTime":1542247259},{"discountValue":"3","expireTime":1542247252},{"discountValue":"3","expireTime":1542247253},{"discountValue":"3","expireTime":1542247253},{"discountValue":"5","expireTime":1542247257}]
posted @ 2018-11-16 16:11  君寻不惑  阅读(130)  评论(0编辑  收藏  举报