Home > Net >  Trying to find the closet date to todays day in an array
Trying to find the closet date to todays day in an array

Time:10-06

I am basically trying to get the object that has the closet date from today, below is the object and what I have so far.

Calls:{
    [
        {
            "CallStartDate": "2022-10-15T00:00:00Z",
        },
        {
            "CallStartDate": "2012-10-16T00:00:00Z",
        },
        {
            "CallStartDate": "2017-12-13T00:00:00Z",
        }
    ]
}

This function below returns the array that is more than today

const poc = callSch.Calls?.filter( el => new Date(el.CallStartDate)> new Date())

any thoughts as the cleanest way possible?

CodePudding user response:

This should work but the structure of your array is wrong though

const timeArray = {
Calls: 
    [
        {
            "CallStartDate": "2022-10-15T00:00:00Z"
        },
        {
            "CallStartDate": "2012-10-16T00:00:00Z"
        },
        {
            "CallStartDate": "2017-12-13T00:00:00Z"
        }
    ]

}

const array = timeArray["Calls"].filter(time => new Date(time["CallStartDate"]) > new Date());

const result = array.reduce((prev, curr) => prev["CallStartDate"] > curr["CallStartDate"] ? curr : prev)
console.log(result);

CodePudding user response:

you can find closset date from today using this..

let Calls = {
    dates: [

        {
            "CallStartDate": "2022-10-15T00:00:00Z",
        },
        {
            "CallStartDate": "2012-10-16T00:00:00Z",
        },
        {
            "CallStartDate": "2017-12-13T00:00:00Z",
        },
        {
            "CallStartDate": "2022-10-01T00:00:00Z",
        },
    ]
}

var temp = Calls.dates.map(d => Math.abs(new Date() - new Date(d.CallStartDate).getTime()));
var idx = temp.indexOf(Math.min(...temp));
console.log(Calls.dates[idx]);

CodePudding user response:

you can use moment.js

const timeArr =[
    {
        "CallStartDate": "2022-10-15T00:00:00Z",
    },
    {
        "CallStartDate": "2012-10-16T00:00:00Z",
    },
    {
        "CallStartDate": "2017-12-13T00:00:00Z",
    }
]

let closetDate = ''
let localTime = moment().format('YYYY-MM-DD');
for(let i = 0; i < timeArr.length; i  ){
    if(moment.utc(timeArr[i].CallStartDate).format('YYYY-MM-DD') > localTime){
        closetDate = timeArr[i].CallStartDate;
    }
}
console.log(closetDate)
<script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>

  • Related