Home > front end >  Filtering elements of array on the basis of dates
Filtering elements of array on the basis of dates

Time:02-10

I have a array as follows:

data = [
{
  "startDate": "2021-08-18T00:00:04.498059"
  "endDate": "2021-08-19T00:00:04.4962889"
},
{
  "startDate": "2021-08-18T00:00:04.498059"
  "endDate": "2021-08-19T00:00:04.4962889"
}
]

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

My try:

newArray = [];
this.data.foreach(element => {
   if((element.startDate - element.endDate) > 7) {
       this.newArray.push(element);
   }
})

Because of the date format I don't know my approach is correct or not. How can I do this correctly?

CodePudding user response:

I think this is the one you are looking for:

*Currently if will store the data if the endDate.day minus startDate.day is bigger than 7 days, but you could change to hours/minutes..... by using getHours(), getMinutes().....

let data = [
{
  startDate: "2021-08-18T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
},
{
  startDate: "2021-08-11T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
}
]


let newArray = [];
data.forEach(element => {
let start = new Date(Date.parse(element.startDate))
let end = new Date(Date.parse(element.endDate))
  if((end.getDate() - start.getDate()) >7) 
      newArray.push(element);
   })
   console.log(newArray)

CodePudding user response:

const data = [
{
  "startDate": "2021-08-18T00:00:04.498059",
  "endDate": "2021-08-19T00:00:04.4962889"
},
{
  "startDate": "2021-08-18T00:00:04.498059",
  "endDate": "2021-08-19T00:00:04.4962889"
}
]
const newData = [];
data.forEach(element => {
  const startDate = new Date(element.startDate);
  const endDate = new Date(element.endDate);
  const difference = endDate.getTime() - startDate.getTime();
  if (difference > 604800000) {
    newData.push(element);
  }
}
);
console.log(newData);

CodePudding user response:

You can check using moment.js library

let data = [
{
  startDate: "2021-08-18T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
},
{
  startDate: "2021-08-11T00:00:04.498059",
  endDate: "2021-08-19T00:00:04.4962889",
}
];
let newArray = [];
for(let i of data){
let end= moment(i['endDate']);
let start= moment(i['startDate']);
let diff = end.diff(start, 'days')
console.log(diff);
if(diff >= 7){
newArray.push(i);
}
}
console.log(newArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>

  •  Tags:  
  • Related