JavaScript代码
- /**
- * @description 2.根据日期时间混合排序
- * @param {Object[]} dataList - 要排序的数组
- * @param {string} property - 传入需要排序的字段
- * @param {boolean} bol - true: 升序;false: 降序;默认为true 升序
- * @return {Object[]} dataList - 返回改变完顺序的数组
- */
- function dateSort(dataList, property, bol = true) {
- dataList.sort(function (a, b) {
- if (bol) {
- // return a[property].localeCompare(b[property]); // 升序
- return Date.parse(a[property]) - Date.parse(b[property]); // 升序
- } else {
- // return b[property].localeCompare(a[property]); // 降序
- return Date.parse(b[property]) - Date.parse(a[property]); // 降序
- }
- })
- return dataList;
- }
- let arrList = [
- { id: 1, name: 'test1', score: 99, dateTime: '2024-03-25 13:51:03' },
- { id: 2, name: 'test2', score: 89, dateTime: '2024-03-24 23:01:52' },
- { id: 3, name: 'test3', score: 102, dateTime: '2024-03-15 01:51:12' },
- { id: 4, name: 'test4', score: 100, dateTime: '2024-03-23 10:30:39' },
- { id: 5, name: 'test5', score: 111, dateTime: '2024-03-23 11:21:42' },
- ]
- // console.log('升序:', dateSort(arrList, 'dateTime')); // 升序
- console.log('降序:', dateSort(arrList, 'dateTime', false)); // 降序