简体   繁体   中英

How do i get 7 consecutive dates(dates are different in array) from an array onwards the current date?

Lets say my current date is 'May 9' , now i wish to get 7 consecutives events(dates) after 'May 9'. Here's my json array sample

[{
    "date": "4 Mar",
    "day": "Mon",
    "holiday_name": "bbb"
},
{
    "date": "7 Mar",
    "day": "Thu",
    "holiday_name": "ccc"
},
{
    "date": "8 Mar",
    "day": "Fri",
    "holiday_name": "ddd"
},
{
    "date": "5 Apr",
    "day": "Fri",
    "holiday_name": "eee"
},
{
    "date": "14 Apr",
    "day": "Sun",
    "holiday_name": "fff"
},
{
    "date": "14 Apr",
    "day": "Sun",
    "holiday_name": "gfgg"
},
{
    "date": "24 Apr",
    "day": "Wed",
    "holiday_name": "ttt"
}, ...
//more in the list]

I get the current date with this,

let day = date.getDate(); const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; let month = monthNames[date.getMonth()]; let appendDate = day + " " + month;

First you can sort the array in ascending order of date. Then use filter and get a new array where date is greater or equal to required date. In your case it is May 9 & in the example below I have considered today's date. After that you can use slice to get required number of days. In your case it is 9 but for example I have considered 2

 let date = [{ "date": "3 Mar", "day": "Mon", "holiday_name": "bbb" }, { "date": "4 Mar", "day": "Mon", "holiday_name": "bbb" }, { "date": "7 Mar", "day": "Thu", "holiday_name": "ccc" }, { "date": "8 Mar", "day": "Fri", "holiday_name": "ddd" }, { "date": "5 Apr", "day": "Fri", "holiday_name": "eee" }, { "date": "14 Apr", "day": "Sun", "holiday_name": "fff" }, { "date": "14 Apr", "day": "Sun", "holiday_name": "gfgg" }, { "date": "24 Apr", "day": "Wed", "holiday_name": "ttt" } ]; let dt = date.sort(function(a, b) { return new Date(a.date) - new Date(b.date) }); function getConsDate(dat) { return dt.filter(function(item) { return new Date(item.date) >= new Date(dat) }).slice(0, 2) } console.log(getConsDate('7 March')) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM