Search code examples
javascriptangulartypescriptdateionic4

Find all missing dates in an JSON object in Javascript / Typescript


In my application I am in need to show missing date range. I tried to get the first and last date but got struck to proceed further. when I tried, I got only the first missing date but the expected output is to display all missing dates from the start date to end date.

https://jsfiddle.net/bgef59x2/3/

https://stackblitz.com/edit/ionic-rknmsc?file=pages%2Fhome%2Fhome.ts

var data={
"dataObj"=[
{"custom_date":"2020-04-13"},
{"custom_date":"2020-04-19"},
{"custom_date":"2020-04-20"},
{"custom_date":"2020-04-21"}
]}

my startDate would be "2020-04-13" and enddate would be "2020-04-21" Expected output:

const result =["2020-04-14","2020-04-15","2020-04-16","2020-04-17","2020-04-18"]

Guide me to achieve the expected result in JavaScript/ Typescript. I have not included momentJs in my application.


Solution

  • Web, just only create a llop from date to date, check if is in the array a push in an array

    missingDates:string[]=[]
    const missingDates: string[] = [];
    
    const from = new Date(this.data[0].custom_date);
    const to = new Date(this.data[this.data.length - 1].custom_date);
    for (let fecha = from;fecha < to;fecha = new Date(fecha.getTime() + 24 * 60 * 60 * 1000)) {
      const date =fecha.getFullYear() +"-" +
        ("00" + (fecha.getMonth() + 1)).slice(-2) +"-" +
        ("00" + fecha.getDate()).slice(-2);
    
      if (!this.data.find(x => x.custom_date == date)) missingDates.push(date);
    }
    console.log(missingDates)