Filter dates in array

Asked

Viewed 141 times

4

Currently I use firebase as my database. I need to take a collection and bring the data of a specific month according to two fields of my collection. firebase doesn’t let us make querys with different fields so I chose to bring everything from the year 2018 and filter in my array the specific month.

I do the following query in firebase:

  let start = new Date('2018-01-01');
  let end = new Date('2018-12-31');
  let ref = db.collection('eventos').where("dt_inicio", ">", start).where("dt_inicio", "<", end).orderBy("dt_inicio", "asc");


  ref.get()
  .then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
     console.log(doc.data());
    });
  });

It returns me to doc.data(), and giving a console.log I get the following return.

inserir a descrição da imagem aqui

I would like to filter the start date and end date by the month of 08/2018.

How should I proceed?

1 answer

0


Using pure JS, you can use a combination of filter and some methods of the object Date. I understood that you want to filter the results by month and year, so it would be like this:

// Recebe o array com os resultados, o mês e o ano no padrão JS. Volta um array filtrado
function filtrarResultados(array, mes, ano) {
    return array.filter(resultado => {
        // Salva o mês e ano de cada campo para poder verificar
        const dt_inicioMes = resultado.dt_inicio.getMonth()
        const dt_inicioAno = resultado.dt_inicio.getFullYear()
        const dt_fimMes = resultado.dt_fim.getMonth()
        const dt_fimAno = resultado.dt_fim.getFullYear()
        return dt_inicioMes == mes && dt_fimMes == mes && dt_inicioAno == ano && dt_fimAno == ano
    })
}

This code snippet will filter and return an array only with the results you have dt_inicio and dt_fim in a given month and a given year.

  • I think what he wants is to filter directly.

  • 1

    Firebase doesn’t allow it. https://firebase.google.com/docs/firestore/query-data/queries#compound_queries

Browser other questions tagged

You are not signed in. Login or sign up in order to post.