來源:https://blog.csdn.net/qq_41033913/article/details/90754217
data是數組,裏面裝了很多對象。way 指定正序反序,pms指定參數
//var data = sortData(data, "order", "YearAndMonth");//將整個數組所有對象,按照日期排序
//var xData = arrayObjectDistinctReturnKey(data, 'YearAndMonth'); //然後去重
var xData0 = arrayObjectDistinctReturnKey(data, 'YearAndMonth'); //先日期去重
var xData = sortData2(xData0, "order");//僅對日期排序
//字符串 時間排序 正序、反序 function sortData(data, way,pms) { if (way == "order") { return data.sort(function (a, b) { //console.log(a,b); var c = Date.parse(a[pms].replace(/-/g, "/")) - Date.parse(b[pms].replace(/-/g, "/")); //console.log(c, Date.parse(a[pms].replace(/-/g, "/")), Date.parse(b[pms].replace(/-/g, "/"))); //這裏的time要根據本身的數據來,後面的正則匹配也要根據自己數據來 return c; }); } else if (way == "back") { return data.sort(function (a, b) { return Date.parse(b[pms].replace(/-/g, "/")) - Date.parse(a[pms].replace(/-/g, "/")); }); } } function sortData2(data, way) { if (way == "order") { return data.sort(function (a, b) { //console.log(a, b); var c = Date.parse(a.replace(/-/g, "/")) - Date.parse(b.replace(/-/g, "/")); //console.log(c, Date.parse(a.replace(/-/g, "/")), Date.parse(b.replace(/-/g, "/"))); //這裏的time要根據本身的數據來,後面的正則匹配也要根據自己數據來 return c; }); } else if (way == "back") { return data.sort(function (a, b) { return Date.parse(b.replace(/-/g, "/")) - Date.parse(a.replace(/-/g, "/")); }); } }
Date.parse(a.replace(/-/g, "/")) 輸出的是時間戳, a-b 是兩個時間戳相減。
文檔:https://www.w3school.com.cn/js/jsref_sort.asp
比較函數應該具有兩個參數 a 和 b,其返回值如下:
- 若 a 小於 b,在排序後的數組中 a 應該出現在 b 之前,則返回一個小於 0 的值。
- 若 a 等於 b,則返回 0。
- 若 a 大於 b,則返回一個大於 0 的值。
// 對象數組去重 利用對象訪問屬性的方法,判斷對象中是否存key function arrayObjectDistinctReturnKey(arr, key) { if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } // console.log('arr', arr) var result = [] if (arr != null && Array.isArray(arr) && arr.length > 0) { var obj = {} for (var i = 0; i < arr.length; i++) { if (arr[i][key]) { if (!obj[arr[i][key]]) { result.push(arr[i][key]) obj[arr[i][key]] = true } } } } // console.log('result', result) return result }