需求:現有一個數組,每一項包含折扣信息與過時時間,現要求先按照折扣大小進行升序排序,而後相同折扣的,按照過時時間進行降序排序。算法
分析數組
查看Array.prototype.sort文檔發現該函數接受一個compare函數做爲參數,sort函數內部藉助該函數的返回值對數組進行排序;函數
而compare函數從sort函數內部接受兩個數組元素(記爲a與b)做爲參數且一共有3種返回值:通過測試發現該compare函數的執行次數與使用者規定的排序規則有關。若數組當前的順序越符合該規則,那麼執行次數越少,不然執行次數越多。測試
動手實現一個compare函數做爲Array.prototype.sort函數的參數;(其實就是編寫排序規則)prototype
排序規則code
數組根據數組元素的折扣與過時時間屬性進行排序,且折扣的權重大於過時時間。對象
代碼實現排序
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; }); }
驗證ip
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}]