Mi objeto de respuesta que contiene startTime , quiero comparar todos los startTimes y obtener la última hora para mostrar en la línea de tiempo. ¿Cómo puedo encontrar la última fecha y hora usando la respuesta de moment.js que recibo?
[{ name:"abc", type:"CALL", startTime:"2021-10-13T07:16:55Z", },{ name:"def", type:"CALL", startTime:"2021-10-13T07:18:57Z", },{ name:"ghi", type:"CALL", startTime:"2021-10-15T07:17:05Z", },{ name:"jkl", type:"CALL", startTime:"2021-11-03T12:07:52Z", }]Mi código -
response.forEach((d)=>{ if(d.type == 'CALL'){ console.log("latest start time ",d); $scope.view(d); //need to pass the obj of latest startTime only $scope.$apply(); }else{ //Something else } })¿Cómo puedo hacer esto usando JavaScript o moment?
Puede ordenar la matriz:
const dates = [{ name:"abc", type:"CALL", startTime:"2021-10-13T07:16:55Z", },{ name:"def", type:"CALL", startTime:"2021-10-13T07:18:57Z", },{ name:"ghi", type:"CALL", startTime:"2021-10-15T07:17:05Z", },{ name:"jkl", type:"CALL", startTime:"2021-11-03T12:07:52Z", }]; const sortedDates = dates.sort((a, b) => moment(a.startTime).diff(moment(b))) Y en la matriz sortedDates en la posición sortedDates[0] tiene la fecha más reciente
Usar la propiedad moment().isBefore puede manejar esto,
const returnLatest =(res)=>{ let latest = res[0]; res.forEach(item=>{ if(moment(item.startTime).isBefore(latest.startTime)){ latest = item; } }); return latest; } const data = [{ name:"abc", type:"CALL", startTime:"2021-10-13T07:16:55Z", },{ name:"def", type:"CALL", startTime:"2021-10-13T07:18:57Z", },{ name:"ghi", type:"CALL", startTime:"2021-10-15T07:17:05Z", },{ name:"jkl", type:"CALL", startTime:"2021-11-03T12:07:52Z", }] console.log(returnLatest(data));Lo solucionará y devolverá el objeto con la última hora de inicio.