1

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;

1 Answer 1

3

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'))

Sign up to request clarification or add additional context in comments.

1 Comment

+1, @Dipesh Lohani I would suggest doing the filtering first then sorting for better performance with large data. And .sort already mutates the array so no need of new reference or sort a copy of input array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.