Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
¿Cómo elimina el último valor de una matriz si no coincide con el primer valor de la siguiente matriz?

Puede que no esté haciendo la pregunta correcta aquí.

Estoy recuperando reservas que tienen la fecha de la primera noche y la última noche y estoy tratando de mostrar en un calendario qué fechas no están disponibles.

La fecha entra como: firstNight: "2022-02-05" y actualmente, debe salir el Sat Feb 05 2022

Para obtener una lista de fechas reservadas, estoy haciendo lo siguiente:

 const bookedDates = bedsData?.map(({ firstNight, lastNight }) => { const newArrivalDate = new Date(firstNight + "T00:00") const newDepartureDate = new Date(lastNight + "T24:00") var getDaysArray = function (start, end) { for ( var arr = [], dt = new Date(start); dt <= end; dt.setDate(dt.getDate() + 1) ) { arr.push(new Date(dt).toDateString()) } return arr } var daylist = getDaysArray(newArrivalDate, newDepartureDate) daylist?.map((v) => v) return daylist.join(", ") })

esto vuelve

 0: undefined 1: "Sat Feb 05 2022, Sun Feb 06 2022, Mon Feb 07 2022, Tue Feb 08 2022, Wed Feb 09 2022, Thu Feb 10 2022, Fri Feb 11 2022, Sat Feb 12 2022" 2: undefined 3: "Sat Feb 12 2022, Sun Feb 13 2022, Mon Feb 14 2022, Tue Feb 15 2022, Wed Feb 16 2022, Thu Feb 17 2022, Fri Feb 18 2022, Sat Feb 19 2022" 4: "Sat Feb 19 2022, Sun Feb 20 2022, Mon Feb 21 2022, Tue Feb 22 2022, Wed Feb 23 2022, Thu Feb 24 2022, Fri Feb 25 2022, Sat Feb 26 2022" 5: undefined 6: undefined 7: "Sat Feb 26 2022, Sun Feb 27 2022, Mon Feb 28 2022, Tue Mar 01 2022, Wed Mar 02 2022, Thu Mar 03 2022, Fri Mar 04 2022, Sat Mar 05 2022" 8: "Sat Mar 05 2022, Sun Mar 06 2022, Mon Mar 07 2022, Tue Mar 08 2022, Wed Mar 09 2022, Thu Mar 10 2022, Fri Mar 11 2022, Sat Mar 12 2022" 9: undefined 10: undefined 11: "Fri Mar 25 2022, Sat Mar 26 2022, Sun Mar 27 2022, Mon Mar 28 2022, Tue Mar 29 2022"

Para mostrar qué fechas están reservadas, estoy usando

 if (bookedDates.join().includes(calDates)) { style.textDecoration = "line-through" style.color = "rgba(0, 0, 0, 0.25)" }

calendario que muestra fechas reservadas / fechas disponibles

El problema al que me enfrento es con las fechas que no tienen un check out y check in el mismo día. El "último día" y el "primer día" de la próxima reserva aún se incluyen en la lista de "fechas reservadas". Sin embargo, deben estar "disponibles" para realizar el check-out o el check-in.

Espero que tenga sentido... ¡bastante perdido con este!

Gracias

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Supongo que en la new Date(lastNight + "T24:00") esa lastNight está en el formato AAAA-MM-DD. Debido a que no hay compensación, la cadena se analizará como local y la fecha se establecerá a las 00:00 del día siguiente, es decir, 2022-02-06T24:00 creará una fecha con un valor de hora idéntico a 2022-02- 07T00:00.

Parece que los datos de su fuente son noches reservadas, que desea utilizar para deshabilitar las fechas que no se pueden seleccionar como días de salida. Por lo tanto, siempre que haya una noche sin reservar, se puede seleccionar el día siguiente como día de salida, incluso si está reservado.

Entonces, al hacer que la matriz de fechas se deshabilite, verifique si hay espacios y elimine la primera fecha reservada. Tendrá que lidiar con esto en la interfaz de usuario para indicar que la fecha no se puede reservar para registrarse.

Otro método sería crear la matriz de noches reservadas, luego, donde haya una brecha, eliminar la noche siguiente, ya que las brechas siempre deben ser dos fechas. El primero está disponible solo para registrarse, el último solo para pagar.

P.ej

 // Parse YYYY-MM-DD as local, not UTC function parseLocal(s) { let [y,m,d] = s.split(/\D/); return new Date(y, m-1, d); } // Format as YYYY-MM-DD function format(date = new Date()) { return date.toLocaleDateString('en-CA'); // YYYY-MM-DD } // Add day to date (modifies date) function addDay(date = new Date()) { date.setDate(date.getDate() + 1); return date; } let bookings = [ {id: 0, firstNight: '2022-02-05', lastNight: '2022-02-09' }, {id: 1, firstNight: '2022-02-10', // Contiguous booking, no gap lastNight: '2022-02-15' }, {id: 2, firstNight: '2022-02-17', // Gap, 17th available for check out lastNight: '2022-02-20' }, {id: 3, firstNight: '2022-02-21', // No gap, not avilable for checkout lastNight: '2022-02-21' }, {id: 4, firstNight: '2022-02-22', // No gap, not avilable for checkout lastNight: '2022-02-22' }, {id: 4, firstNight: '2022-02-24', // Gap, avilable for checkout lastNight: '2022-02-24' }, {id: 4, firstNight: '2022-02-25', // No gap, not avilable for checkout lastNight: '2022-02-25' } ] let bookedDates = bookings.map( ({firstNight, lastNight}) => [parseLocal(firstNight), parseLocal(lastNight)] ).reduce((dates, [firstNight, lastNight], i, mapDates) => { // If lastNight of previous booking is not prevNight, // don't add firstNight to array let prevBookedNight = i? mapDates[i-1][1] : null; if (i && format(addDay(prevBookedNight)) != format(firstNight)) { addDay(firstNight); } while (firstNight <= lastNight) { dates.push(format(firstNight)); firstNight.setDate(firstNight.getDate() + 1); } return dates; },[]); console.log('Not available for check in or out:\n' + bookedDates.join('\n'));

about 4 years ago · Juan Pablo Isaza Report

0

No estoy seguro de haber entendido, pero ¿no es solo una confusión con los límites de inicio y fin de su bucle for? ¿Intentaste inicializar con

 if (firstNight!==lastNight) { const newArrivalDate = new Date(firstNight + "T24:00") const newDepartureDate = new Date(lastNight + "T00:00") } else { const newArrivalDate = new Date(firstNight + "T00:00") const newDepartureDate = new Date(lastNight + "T00:00") }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!