Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
trying to sort bookings by date and hours react.js

this my first post in StackOverflow, so sorry if I am not posting properly.

Here's my problem, as the title says I want to sort my bookings by date and hour, but the problem I am facing is that the bookings appears in order you create them.

this is the chunk of code:

<Card className="my-4 booking-profile">
                <Card.Body>
                    <Card.Title>
                        {bookings.map((booking, index) => {
                            console.log(index);
                            return (
                                <ul key={booking.id}>
                                    <li>
                                        <span>
                                            {" "}
                                            Tu reserva: {booking.day}/{booking.month}/{booking.year} a las{" "}
                                            {booking.hour}:{booking.minutes}
                                        </span>
                                        <i
                                            onClick={() => {
                                                deleteBooking(index);
                                            }}
                                            className="fas fa-trash-alt delete"></i>
                                    </li>
                                </ul>
                            );
                        })}
                    </Card.Title>
                </Card.Body>
            </Card>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to sort it but the problem is that you cant compare day of the week so you need to assign value to each day, you can add another sort for the month and repeat the same process like this:


const sorter = {
  //"sunday": 0, // << if sunday is first day of week
  "monday": 1,
  "tuesday": 2,
  "wednesday": 3,
  "thursday": 4,
  "friday": 5,
  "saturday": 6,
  "sunday": 7
}

{bookings.sort(function sortByDay(a, b) {
  let day1 = a.day.toLowerCase();
  let day2 = b.day.toLowerCase();
  return sorter[day1] - sorter[day2];
}).map((booking, index) => { ...

Then for the time (hours and minutes) it depends if you are using am pm format or not but the process is the same.

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd suggest using Array.sort() with your own custom sorter, say bookingSorter()

We'll use the JavaAcript Date object to help us sort the values, creating a new Date object for each booking, then comparing it to the others in the sort function.

const bookings = [
    { year: 2021, month: 12, day: 20, hour: 07, minutes: 30 },
    { year: 2021, month: 11, day: 4, hour: 15, minutes: 20 },
    { year: 2021, month: 11, day: 9, hour: 16, minutes: 20 },
    { year: 2021, month: 11, day: 4, hour: 15, minutes: 25 }
];

function getBookingDate({ year, month, day, hour, minutes}) {
    return new Date(year, month - 1, day, hour, minutes);
}

function bookingSorter(a, b) {
    return getBookingDate(a) - getBookingDate(b);
}

function formatBooking(booking) {
    return getBookingDate(booking).toLocaleString('sv');
}


const sortedBookings = [...bookings].sort(bookingSorter);

console.log('Unsorted bookings:', bookings.map(formatBooking));    
console.log('Sorted bookings:', sortedBookings.map(formatBooking))
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda