gpt4 book ai didi

javascript - Lodash _.sortBy 基于创建日期和时间

转载 作者:行者123 更新时间:2023-12-01 00:33:33 24 4
gpt4 key购买 nike

let notesInfo = []

if (_.isArray(result)) {
console.log(result, '-----------');
notesInfo = _.sortBy(result, ['modifiedDate']);
} else {
notesInfo = result;
}

console.log(notesInfo)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

我使用此代码根据创建日期和时间显示笔记。使用 lodash 的 sortBy 方法,最新添加的注释应该位于顶部。如何实现这一目标?提前致谢。

最佳答案

如果您希望将最新的项目放在最前面,而其余的则按升序排列,那么您可以按升序正常排序。由于最后一个元素是最新的,因此您可以使用 Array#pop 将其旋转到数组的前面。和 Array#unshift :

let result = [
{ modifiedDate: "2019-02-01", name: "february" },
{ modifiedDate: "2019-04-01", name: "april" },
{ modifiedDate: "2019-01-01", name: "january" },
{ modifiedDate: "2019-03-01", name: "march" }
];

//sort ascending
let notesInfo = _.sortBy(result, ['modifiedDate']);

//take the most recent (last)
var lastElement = notesInfo.pop();

//place it first
notesInfo.unshift(lastElement);

console.log(notesInfo);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

如果您希望项目按降序排列,那么您应该使用 _.orderBy而不是 _.sortBy:

let result = [
{ modifiedDate: "2019-02-01", name: "february" },
{ modifiedDate: "2019-04-01", name: "april" },
{ modifiedDate: "2019-01-01", name: "january" },
{ modifiedDate: "2019-03-01", name: "march" }
];

//sort descending
let notesInfo = _.orderBy(result, ['modifiedDate'], ['desc']);

console.log(notesInfo);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

关于javascript - Lodash _.sortBy 基于创建日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com