如何按日期数组(desc)排序,同时保持(asc)相同的日期时间



我需要用时间降序排列一个日期数组,但时间用lodash保持升序。

const supplierDates = ["2022-02-14 10:00", "2022-02-14 08:00", "2022-02-14 09:00", "2022-02-17 19:00", "2022-02-18 18:00"
results = _.orderBy(supplierDates, suppDate => suppDate, ['desc']);

这按降序对数组进行排序,但我有兴趣在同一天(在本例中为2月14日(的中保持升序

发生这种情况是因为您在对字符串进行排序,而您希望对日期进行排序。

首先,按照asc顺序订购整个日期,以保持每天的小时数。

然后使用substring从字符串中仅提取日期,然后使用Date.parse解析为日期,以便对其进行排序:

const supplierDates = ["2022-02-14 08:00", "2022-02-14 10:00", "2022-02-14 07:00", "2022-02-17 19:00", "2022-02-18 18:00"];
const initialOrder = _.orderBy(supplierDates, suppDate => Date.parse(suppDate), ['asc']);
const results = _.orderBy(initialOrder, suppDate => Date.parse(suppDate.substring(0, 10)), ['desc']);
console.log(results);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

最新更新