-2

Trying to filter an array of objects by start and end object values.

start = "Feb-2015"
end = "Jul-2015"

result = array.sort(2,7);

have tried this but I have dates, I will be not knowing the index of it. array = [ { "date": "Jan-2015" }, { "date": "Feb-2015" }, { "date": "Mar-2015" }, { "date": "Apr-2015" }, { "date": "May-2015" }, {, "date": "Jun-2015" }, { "date": "Jul-2015" }, { "date": "Aug-2015" } ]

expected output:-

result = [
      {
        "date": "Feb-2015"
      },
      {
        "date": "Mar-2015"
      },
      {
        "date": "Apr-2015"
      },
      {    "date": "May-2015"
      },
      {,
        "date": "Jun-2015"
      },
      { 
        "date": "Jul-2015"
      }
]
2
  • Check this out stackoverflow.com/questions/37167102/… Commented Sep 24, 2019 at 12:29
  • filter = data.filter(function(d){ var date = new Date(d.metric_name); return (date >= new Date(start) && date <= new Date(end)) })
    – kiran
    Commented Sep 24, 2019 at 13:00

2 Answers 2

0

const data = [{"date":"Jan-2018"},{"date":"Feb-2015"},{"date":"Mar-2015"},{"date":"Apr-2015"},{"date":"May-2015"},{"date":"Jun-2015"},{"date":"Jul-2015"},{"date":"Aug-2015"}];

console.log(data.sort((a, b) => { return new Date(a.date) - new Date(b.date)}));

0

Use below.

array = [{
    "date": "Jan-2015"
  },
  {
    "date": "Aug-2015"
  },
  {
    "date": "Feb-2015"
  },
  {
    "date": "Mar-2015"
  },
  {
    "date": "Apr-2015"
  },
  {
    "date": "May-2015"
  },
  {
    "date": "Jun-2015"
  },
  {
    "date": "Jul-2015"
  }

];

//filter
sort = (arr, start, end) => {
  let arrayFiltered = arr.filter((obj) => {
    obj.dateObj = new Date(obj.date.substring(0, 3) + obj.date.substring(4, 8));

    return (obj.dateObj.getMonth() + 1) >= start && (obj.dateObj.getMonth() + 1) <= end;
  });

  console.log(arrayFiltered.sort(obj => obj.dateObj));
};

sort(array, 2, 7);

Output

[{
  "date": "Feb-2015",
  "dateObj": "2015-01-31T18:30:00.000Z"
}, {
  "date": "Mar-2015",
  "dateObj": "2015-02-28T18:30:00.000Z"
}, {
  "date": "Apr-2015",
  "dateObj": "2015-03-31T18:30:00.000Z"
}, {
  "date": "May-2015",
  "dateObj": "2015-04-30T18:30:00.000Z"
}, {
  "date": "Jun-2015",
  "dateObj": "2015-05-31T18:30:00.000Z"
}, {
  "date": "Jul-2015",
  "dateObj": "2015-06-30T18:30:00.000Z"
}]
2
  • filter = data.filter(function(d){ var date = new Date(d.metric_name); return (date >= new Date(start) && date <= new Date(end)) })
    – kiran
    Commented Sep 24, 2019 at 13:01
  • this will do ty :)
    – kiran
    Commented Sep 24, 2019 at 13:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.