Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter array of objects based on month and year

I want to display the objects based on the current month and year

This filters the objects based on the month, I need to filter objects based on the year also.

var array = [{
    title: "a",
    date: "2018-03-29"
  }, {
    title: "b",
    date: "2018-04-13"
  }, {
    title: "c",
    date: "2018-04-12"
  }, {
    title: "leave",
    date: "2018-04-11"
  }, {
    title: "d",
    date: "2018-06-16"
  }],
  currentMonth = new Date().getMonth() + 1,
  events = array.filter(e => {
    var [_, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
    return currentMonth === +month;
  });
console.log(events);
like image 524
Mohammed Abdul kadhir Avatar asked Oct 16 '22 17:10

Mohammed Abdul kadhir


1 Answers

Well to filter by year and month, you just need to get the currentYear along with currentMonth, and then get the year and month of the iterated date.

This is how should be your code:

//Get the currentYear and the currentMonth
currentMonth = new Date().getMonth() + 1,
currentYear = new Date().getFullYear(),

//Get the year and month from the iterated date
var [year, month] = e.date.split('-');

//Then filter the dates
events = array.filter(e => {
    var [year, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
    return (currentMonth === +month) && (currentYear == year);
});

Demo:

var array = [{
    title: "a",
    date: "2018-03-29"
  }, {
    title: "b",
    date: "2018-04-13"
  }, {
    title: "c",
    date: "2018-04-12"
  }, {
    title: "leave",
    date: "2018-04-11"
  }, {
    title: "d",
    date: "2018-06-16"
  }],
  currentMonth = new Date().getMonth() + 1,
  currentYear = new Date().getFullYear(),
  events = array.filter(e => {
    var [year, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
    return (currentMonth === +month) && (currentYear == year);
  });
console.log(events);
like image 131
cнŝdk Avatar answered Oct 20 '22 22:10

cнŝdk