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方法放在顶部。如何实现呢?预先感谢。
答案 0 :(得分:2)
如果您要首先获取最新的项目,而其余的则按升序排列,则可以按升序正常排序。由于最后一个元素是最新元素,因此可以使用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>
答案 1 :(得分:0)
让我们假设这是您的数据:
var result = [{
name: "Mango",
modifiedDate: "Mon Oct 10 2019 00:00:00 GMT-0700 (PDT)"
}, {
name: "Banana",
modifiedDate: "Sun Oct 9 2019 00:00:00 GMT-0700 (PDT)"
}, {
name: "Kivi",
modifiedDate: "Sat Oct 8 2019 00:00:00 GMT-0700 (PDT)"
}];
原生Array.prototype.sort()
result.sort(function compare(a, b) {
var dateA = new Date(a.modifiedDate);
var dateB = new Date(b.modifiedDate);
return dateA - dateB;
});
或者用lodash
output = _.sortBy(result, function(dateObj) {
return new Date(dateObj.modifiedDate);
});
答案 2 :(得分:0)
let notesInfo = []
if (_.isArray(result)) {
console.log(result, '-----------');
notesInfo = _.sortBy(result, ['modifiedDate']).reverse();
} else {
notesInfo = result;
}
console.log(notesInfo)
这按预期工作。谢谢