我正在动态地向列表中添加新项目,并根据状态先排序,然后按日期排序。工作代码
每当我向列表中添加一个新项目时,我希望列表显示错误的状态项,其中最新的日期首先按desc显示,然后按date desc显示真值项
added item ={"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test6"}
无序列表:-
var itemlist = [{
"Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
"Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];
预期结果:-
var itemlist = [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test6"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
"Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
"Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];
获得的结果:-
var itemlist = [{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test6"},{
"Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
"Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];
使用的方法:-
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : (a.Status ? 1 : -1 || +new Date(b.Date)- +new Date(a.Date)));
3条答案
按热度按时间fhg3lkii1#
你可以分类
Status
随着值增量的增加Date
随着字符串的下降。jvidinwx2#
您可以在中使用逻辑or运算符
sort
回拨。bcs8qyzn3#
首先
Unordered list:-
及Expected Result:-
示例数据中的元素数不相同。当您请求帮助时,请尝试正确获取示例数据。解决方案:
说明:
如果
.Status
不匹配我们希望元素先为false,否则如果.Status
匹配我们想要比较日期。