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/[email protected]/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/[email protected]/lodash.min.js"></script>
关于javascript - Lodash _.sortBy基于创建的日期和时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58318458/