我有两个数组
var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"];
var eventDetails= [{
"source" : "application"
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application"
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application"
"DateTime": "2016-11-05 11:20:00",
"eventNname" : "CUSTOM CLEARANCE"
}];
如果最新的eventName出现在“events”数组中,我需要从eventDetails数组中显示最新的eventName(最新的日期和时间)。否则它应该返回null(如果最新更新记录中的eventName不包含事件数组中的任何值)。
答案 0 :(得分:1)
您可以通过几种不同的方式完成此操作。一个简单的解决方案是按日期排序事件,然后抓住你需要的那个(在这种情况下是第一个):
var eventDetails= [{
"source" : "application",
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
}, {
"source" : "application",
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
}, {
"source" : "application",
"DateTime": "2016-11-05 11:20:00",
"eventNname" : "CUSTOM CLEARANCE"
}];
var last = eventDetails.sort(function(prev, next) {
return new Date(next.DateTime) - new Date(prev.DateTime);
})[0];
var lastEventName = last.eventName;
if (events.indexOf(lastEventName) >= 0) {
// Return true
} else {
// Return false
}
您还可以循环浏览所有事件并跟踪最新事件:
var last = eventDetails[0];
for (var i = 1; i < eventDetails.length; i++) {
if (eventDetails[i].DateTime > last.DateTime) {
last = eventDetails[i];
}
}
var lastEventName = last.eventName;
if (events.indexOf(lastEventName) >= 0) {
// Return true
} else {
// Return false
}
答案 1 :(得分:0)
您可以使用javascript sort
方法并使用indexOf
检查events
数组中是否存在值
var events=["DELIVERED", "REACHED WAREHOUSE", "OUT TO DELEVERY", "DEPARTED"];
var eventDetails= [{
"source" : "application",
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application",
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application",
"DateTime": "2016-11-05 11:20:00",
"eventName" : "CUSTOM CLEARANCE"
}];
eventDetails = eventDetails.sort(function(a,b){
return new Date(b.DateTime) - new Date(a.DateTime)
})
if( events.indexOf(eventDetails[0].eventName) !== -1 ){
console.log('true')
}else{
console.log('false')
}