Estoy recibiendo una respuesta de mi API donde se da start_date . Quiero extraer la id de json cuya próxima fecha y hora es la más cercana a la fecha y hora actual.
[ { "expected": { "id": 1, "end_time": "2021-10-01T06:35:00.659Z", "start_time": "2021-10-01T06:35:00.659Z" } }, { "expected": { "id": 2, "end_time": "2021-09-30T17:08:29.307Z", "start_time": "2021-09-30T17:08:29.307Z" } }, { "expected": { "id": 3, "end_time": "2021-10-01T09:49:18.574Z", "start_time": "2021-10-01T09:49:18.574Z" } }, { "expected": { "id": 4, "end_time": "2021-09-30T17:08:29.303Z", "start_time": "2021-09-30T15:08:29.303Z" } }, ] Como puede ver, según la fecha id:2 y id:4 tiene la fecha de inicio más start_date a la fecha actual, y luego según la hora id:4 es la más cercana.
No puedo averiguar cómo extraer esta id . Lo he estado intentando durante horas pero no me he acercado a la solución. Por favor ayuda.
Paso 1: usar Array.sort by Date.getTime() cuando se compara con la fecha y hora actual.
Paso 2: devuelve el primer elemento de la matriz ordenada.
const inputArray = [{ "expected": { "id": 1, "end_time": "2021-10-01T06:35:00.659Z", "start_time": "2021-10-01T06:35:00.659Z" } }, { "expected": { "id": 2, "end_time": "2021-09-30T17:08:29.307Z", "start_time": "2021-09-30T17:08:29.307Z" } }, { "expected": { "id": 3, "end_time": "2021-10-01T09:49:18.574Z", "start_time": "2021-10-01T09:49:18.574Z" } }, { "expected": { "id": 4, "end_time": "2021-09-30T17:08:29.303Z", "start_time": "2021-09-30T15:08:29.303Z" } }, ] const today = new Date().getTime(); const result = inputArray.sort((a, b) => { const diffA = new Date(a.expected.start_time).getTime() - today; const diffB = new Date(b.expected.start_time).getTime() - today; return diffA - diffB; })[0]; console.log(result.expected.id);Mis datos
const data = [ { "expected": { "id": 1, "end_time": "2021-10-01T06:35:00.659Z", "start_time": "2021-10-01T13:35:00.659Z" } }, { "expected": { "id": 2, "end_time": "2021-09-30T17:08:29.307Z", "start_time": "2021-09-30T17:08:29.307Z" } }, { "expected": { "id": 3, "end_time": "2021-10-01T09:49:18.574Z", "start_time": "2021-10-05T09:49:18.574Z" } }, { "expected": { "id": 4, "end_time": "2021-09-30T17:08:29.303Z", "start_time": "2021-09-30T15:08:29.303Z" } }]Luego, he creado una función getNextTime()
getNextTime = () => { let nextTimeData = []; const sortedData = data.sort((a, b) => new Date(b.expected.start_time) - new Date(a.expected.start_time)) sortedData.forEach((element) => { if (new Date() <= new Date(element.expected.start_time)) { nextTimeData.push(element) } }) return nextTimeData }Esa función le brinda toda la próxima fecha y hora, puede usar el último índice de nextTimeData como fecha y hora de armario como:
let data = this.getNextTime(); console.log('closet date time id ::', data[data.length - 1].expected.id);