Help to perform javascript start date and end date filter

Asked

Viewed 1,504 times

0

I am trying to perform a filter between the initial and final date chosen by the user. I have some objects that look like:

let objetos = [
   {nome: 'teste01', data: '03/09/2019'}
   {nome: 'teste02', data: '03/10/2019'}
   {nome: 'teste03', data: '03/11/2019'}
   {nome: 'teste04', data: '03/12/2019'}
   {nome: 'teste05', data: '03/01/2020'}
]

What I hope is to return by the objects containing the following for example, the objects with the name of teste01 and teste02 that are within the date range informed:

let dataInicial: string = '01/09/2019';
let dataFinal: string = '31/10/2019';
let objetosFiltrados = objetos.filter(result => {
   return result.data >= dataInicial && result.data <= dataFinal;
})
console.log(objetosFiltrados);

But when I perform it it brings me all the records, what the correct way to do it please?

  • You are using the data field in string format, you would have to convert to numbers or date to make differentiation of larger and smaller. Also to work dates in the dd/mm/yyyy format you will have to develop a routine to convert to an American format or use a Moment.js library.

1 answer

1


You can use this code that works:

let objetos = [
   {nome: 'teste01', data: '03/09/2019'},
   {nome: 'teste02', data: '03/10/2019'},
   {nome: 'teste03', data: '03/11/2019'},
   {nome: 'teste04', data: '03/12/2019'},
   {nome: 'teste05', data: '03/01/2020'}
]

function converteData(DataDDMMYY) {
    const dataSplit = DataDDMMYY.split("/");
    const novaData = new Date(parseInt(dataSplit[2], 10),
                  parseInt(dataSplit[1], 10) - 1,
                  parseInt(dataSplit[0], 10));
    return novaData;
}


let dataInicial = converteData('01/09/2019');
let dataFinal = converteData('31/10/2019');
let objetosFiltrados = objetos.filter(result => {
   return converteData(result.data) >= dataInicial && converteData(result.data) <= dataFinal;
})
console.log(objetosFiltrados);

  • 1

    Thank you brother, solved here for me.

Browser other questions tagged

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